2

我正在编写一个 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)
4

4 回答 4

5

http://www.skymind.com/~ocrow/python_string/讨论了 Python 中连接字符串的几种方法,并评估了它们的性能。

于 2009-03-17T07:08:57.443 回答
4

你不想使用 re.split 吗?

import re
re.split("[,; ]+", "coucou1 ,   coucou2;coucou3")
于 2009-03-17T07:08:48.100 回答
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
于 2009-03-17T07:36:10.000 回答
1

您可以使用以下方法拆分输入re.split()

>>> splitchars=' \t|!?.;:"'
>>> re.split("[%s]" % splitchars, "one\ttwo|three?four")
['one', 'two', 'three', 'four']
>>> 

编辑:如果您splitchars可能包含特殊字符,例如]or ^,您可以使用re.escpae()

>>> re.escape(splitchars)
'\\ \\\t\\|\\!\\?\\.\\;\\:\\"'
>>> re.split("[%s]" % re.escape(splitchars), "one\ttwo|three?four")
['one', 'two', 'three', 'four']
>>> 
于 2009-03-17T07:25:01.477 回答