簡體   English   中英

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

[英]Fast/Efficient counting of list of space delimited strings in Python

鑒於輸入:

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個單詞。

假設您使用的是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))

您的問題的答案是分析

以下是一些分析工具:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM