考虑到结果中的标点符号,如何在python中拆分字符串?
以下代码:
s = "Hello, my name is Robert."
s_splitted = s.split()
将给出输出:
["Hello,","my","name","is","Robert."]
如何获得以下结果?
["Hello",",","my","name","is","Robert","."]
答案 0 :(得分:0)
正则表达式可以处理此问题。
import re
s = "Hello, my name is Robert."
s_splitted = [part for part in re.split(r'\b|\s', s) if part != '']
# ['Hello', ',', 'my', 'name', 'is', 'Robert']
答案 1 :(得分:0)
this回答您的问题吗?
所以在您的情况下:
import re
s = "Hello, my name is Robert."
items = re.findall(r"[\w']+|[.,!?;]", s)