在Python中快速/高效地计算空格分隔字符串列表

时间:2017-04-26 01:47:19

标签: python dictionary counter itertools chain

鉴于输入:

x = ['foo bar', 'bar blah', 'black sheep']

我可以这样做来获取空格分隔字符串列表中每个单词的计数:

from itertools import chain
from collections import Counter
c = Counter(chain(*map(str.split, x)))

或者我可以简单地迭代并获得:

c = Counter()
for sent in x:
    for word in sent.split():
        c[word]+=1

[OUT]:

Counter({'bar': 2, 'sheep': 1, 'blah': 1, 'foo': 1, 'black': 1})

问题是如果字符串的输入列表非常庞大会更有效吗?是否有其他方法可以实现相同的计数器对象?

想象一下,它是一个文本文件对象,有数十亿行,每行10-20个单词。

2 个答案:

答案 0 :(得分:0)

假设您使用的是Python 3x,chain(*map(str.split, x))和简单迭代都将从每行依次创建中间列表;在任何一种情况下,这都不会占用太多内存。性能应非常接近,可能与实现有关。

但是,创建生成器函数以提供Counter()是最有效的内存方式。无论哪种方式使用string.split(),它都会创建不必要的中间列表。如果你有一条特别长的线,这可能会导致放缓,但说实话,它不太可能。

下面描述这种发生器功能。请注意,为了清晰起见,我使用了可选的输入法。

from typing import Iterable, Generator
def gen_words(strings: Iterable[str]) -> Generator[str]:
    for string in strings:
        start = 0
        for i, char in enumerate(string):
            if char == ' ':
                if start != i:
                    yield string[start:i]
                start = i
        if start != i:
            yield string[start:i]
c = counter(gen_words(strings))

答案 1 :(得分:0)

您的问题的答案是profiling

以下是一些分析工具:

相关问题