In [70]: re.findall(r"[^,.:;' ]+|[,.:;']", "I want that one, it is great.")
Out[70]: ['I', 'want', 'that', 'one', ',', 'it', 'is', 'great', '.']
In [76]: re.findall(r"[^,.:;' ]+|[,.:;']", "I don't.")
Out[76]: ['I', 'don', "'", 't', '.']
正则表达式 [^,.:;' ]+|[,.:;'] 匹配(除 ,、.、:、;、' 或文字空格之外的 1 个或多个字符)或(文字字符 @987654332 @、.、:、; 或 ')。
或者,使用regex module,您可以使用[:punct:] 字符类轻松扩展它以包含所有punctuation and symbols:
In [77]: import regex
在 Python2 中:
In [4]: regex.findall(ur"[^[:punct:] ]+|[[:punct:]]", u"""A \N{ARABIC SEMICOLON} B""")
Out[4]: [u'A', u'\u061b', u'B']
In [6]: regex.findall(ur"[^[:punct:] ]+|[[:punct:]]", u"""He said, "I don't!" """)
Out[6]: [u'He', u'said', u',', u'"', u'I', u'don', u"'", u't', u'!', u'"']
在 Python3 中:
In [105]: regex.findall(r"[^[:punct:] ]+|[[:punct:]]", """A \N{ARABIC SEMICOLON} B""")
Out[105]: ['A', '؛', 'B']
In [83]: regex.findall(r"[^[:punct:] ]+|[[:punct:]]", """He said, "I don't!" """)
Out[83]: ['He', 'said', ',', '"', 'I', 'don', "'", 't', '!', '"']
请注意,如果您希望 [:punct:] 匹配 unicode 标点符号或符号,请将 unicode 作为第二个参数传递给 regex.findall,这一点很重要。
在 Python2 中:
import regex
print(regex.findall(r"[^[:punct:] ]+|[[:punct:]]", 'help؛'))
print(regex.findall(ur"[^[:punct:] ]+|[[:punct:]]", u'help؛'))
打印
['help\xd8\x9b']
[u'help', u'\u061b']