【问题标题】:Effective way to iteratively append to a string in Python?在Python中迭代附加到字符串的有效方法?
【发布时间】:2010-10-13 18:53:49
【问题描述】:

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

【问题讨论】:

  • 太糟糕了......所以这里有人提出了最佳答案,说内置拆分允许放置多个拆分字符。你说他的代码丑陋,他删除了他的消息。

标签: python string split append generator


【解决方案1】:

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

【讨论】:

  • 这正是我所需要的。谢谢。 cStringIO 似乎是我用例的最佳选择。
  • 为了它的价值:我破解了那个测试用例,直到它在我的 Python 2.5 安装上运行,并发现方法 6(feed ''.join a list comprehension)始终是最快的。 6 个带有生成器表达式的结果 较慢,但仍然是第二快的。
  • 按照从最快到最慢的顺序,这些方法最终是 6、7、4、1、5、3、2。(7 是 6,括号被去掉,使其成为生成器表达式而不是列表理解)。我无法测量内存使用情况。
【解决方案2】:

你不想使用 re.split?

import re
re.split("[,; ]+", "coucou1 ,   coucou2;coucou3")

【讨论】:

  • 完全没有想到。会考虑的。谢谢!
【解决方案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

【讨论】:

    【解决方案4】:

    你可以使用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']
    >>> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 2023-01-25
      相关资源
      最近更新 更多