我需要创建一个tokenizer,它将用逗号分割字符串。
使用split可以做到这一点
re.split(',+', str)但我需要使用编译。我试过了
text = "5g, dynamic vision sensor (dvs), 3-d reconstruction, neuromorphic engineering, neural networks, humanoid robots, neuromorphics, closed loop systems, field programmable gate arrays, spiking motor controller, neuromorphic implementation, icub, relation neural network"
pattern = re.compile(r'[a-z0-9\(\)-]+')
re.findall(pattern, text)输出结果是
['5g', 'dynamic', 'vision', 'sensor', '(dvs)', '3-d', 'reconstruction', 'neuromorphic', 'engineering', 'neural', 'networks', 'humanoid', 'robots', 'neuromorphics', 'closed', 'loop', 'systems', 'field', 'programmable', 'gate', 'arrays', 'spiking', 'motor', 'controller', 'neuromorphic', 'implementation', 'icub', 'relation', 'neural', 'network']所需输出为
['5g', 'dynamic vision sensor (dvs)', '3-d reconstruction', 'neuromorphic engineering', 'neural networks', 'humanoid robots', 'neuromorphics', 'closed loop systems', 'field programmable gate arrays', 'spiking motor controller', 'neuromorphic implementation', 'icub', 'relation neural network']发布于 2021-08-05 12:34:01
正如@mama所说,你不需要为此使用正则表达式,但是如果你特别想使用re.compile,你可以用下面的代码来实现:
text = "5g, dynamic vision sensor (dvs), 3-d reconstruction, neuromorphic engineering, neural networks, humanoid robots, neuromorphics, closed loop systems, field programmable gate arrays, spiking motor controller, neuromorphic implementation, icub, relation neural network"
pattern = re.compile(r'([\sa-z0-9\(\)-]+)')
L=re.findall(pattern, text)
L=[l.lstrip(" ") for l in L]

发布于 2021-08-05 12:27:14
不要为此使用正则表达式。只需使用python内置的split()函数
text = "5g, dynamic vision sensor (dvs), 3-d reconstruction, neuromorphic engineering, neural networks, humanoid robots, neuromorphics, closed loop systems, field programmable gate arrays, spiking motor controller, neuromorphic implementation, icub, relation neural network"
print(text.split(', '))发布于 2021-08-05 12:36:32
试试这个模式:[a-z0-9() -]+(?=,|$)
代码:
text = "5g, dynamic vision sensor (dvs), 3-d reconstruction, neuromorphic engineering, neural networks, humanoid robots, neuromorphics, closed loop systems, field programmable gate arrays, spiking motor controller, neuromorphic implementation, icub, relation neural network"
pattern = re.compile(r'[a-z0-9() -]+(?=,|$)')
print([x.strip() for x in re.findall(pattern, text)])输出:
['5g', 'dynamic vision sensor (dvs)', '3-d reconstruction', 'neuromorphic engineering', 'neural networks', 'humanoid robots', 'neuromorphics', 'closed loop systems', 'field programmable gate arrays', 'spiking motor controller', 'neuromorphic implementation', 'icub', 'relation neural network']https://stackoverflow.com/questions/68666529
复制相似问题