在Python中迭代附加到字符串的有效方法?

2024-06-26 00:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: orand代码textinifissome