我正在编写一个Python函数来将文本拆分为单词,忽略指定的标点符号。这是一些工作代码。我不相信从列表中构造字符串(代码中的buf = [])是有效的。有没有人建议更好的方法来做到这一点?
def getwords(text, splitchars=' \t|!?.;:"'):
"""
Generator to get words in text by splitting text along specified splitchars
and stripping out the splitchars::
>>> list(getwords('this is some text.'))
['this', 'is', 'some', 'text']
>>> list(getwords('and/or'))
['and', 'or']
>>> list(getwords('one||two'))
['one', 'two']
>>> list(getwords(u'hola unicode!'))
[u'hola', u'unicode']
"""
splitchars = set(splitchars)
buf = []
for char in text:
if char not in splitchars:
buf.append(char)
else:
if buf:
yield ''.join(buf)
buf = []
# All done. Yield last word.
if buf:
yield ''.join(buf)
答案 0 :(得分:5)
http://www.skymind.com/~ocrow/python_string/讨论了在Python中连接字符串的几种方法,并评估了它们的性能。
答案 1 :(得分:4)
您不想使用re.split?
import re
re.split("[,; ]+", "coucou1 , coucou2;coucou3")
答案 2 :(得分:3)
您可以使用re.split
re.split('[\s|!\?\.;:"]', text)
但是,如果文本非常大,则生成的数组可能会消耗太多内存。那你可以考虑re.finditer:
import re
def getwords(text, splitchars=' \t|!?.;:"'):
words_iter = re.finditer(
"([%s]+)" % "".join([("^" + c) for c in splitchars]),
text)
for word in words_iter:
yield word.group()
# a quick test
s = "a:b cc? def...a||"
words = [x for x in getwords(s)]
assert ["a", "b", "cc", "def", "a"] == words, words
答案 3 :(得分:1)
您可以使用re.split()
分割输入:
>>> splitchars=' \t|!?.;:"'
>>> re.split("[%s]" % splitchars, "one\ttwo|three?four")
['one', 'two', 'three', 'four']
>>>
编辑:如果您的splitchars
可能包含]
或^
等特殊字符,则可以使用re.escpae()
>>> re.escape(splitchars)
'\\ \\\t\\|\\!\\?\\.\\;\\:\\"'
>>> re.split("[%s]" % re.escape(splitchars), "one\ttwo|three?four")
['one', 'two', 'three', 'four']
>>>