计算三个单词的频率

时间:2018-08-21 13:20:23

标签: python string python-3.x counter

我有下面的代码来查找两个单词短语的频率。我需要对三个单词短语执行相同的操作。

但是,以下代码似乎不适用于3个单词的短语。

from collections import Counter
import re

sentence = "I love TV show makes me happy, I love also comedy show makes me feel like flying"
words = re.findall(r'\w+', sentence)
two_words = [' '.join(ws) for ws in zip(words, words[1:])]
wordscount = {w:f for w, f in Counter(two_words).most_common() if f > 1}
wordscount
{'show makes': 2, 'makes me': 2, 'I love': 2}

4 个答案:

答案 0 :(得分:2)

我建议将该功能分解为a seperate function

def nwise(iterable, n):
    """
    Iterate over n-grams of an iterable.
    Has a bit of an overhead compared to pairwise (although only during
    initialization), so the two functions are implemented independently.
    """
    iterables = [iter(iterable) for _ in range(n)]
    for index, it in enumerate(iterables):
        for _ in range(index):
            next(it)
    yield from zip(*iterables)

那你就可以做

two_words = [" ".join(bigram) for bigram in nwise(words, 2))]

three_words = [" ".join(trigram) for trigram in nwise(words, 3))]

,依此类推。 然后,您可以使用collections.Counter

three_word_counts = Counter(" ".join(trigram) for trigram in nwise(words, 3))

答案 1 :(得分:2)

您可以在可重复的3字分组中使用collections.Counter。后者是通过生成器理解和列表切片构造的。

from collections import Counter

three_words = (words[i:i+3] for i in range(len(words)-2))
counts = Counter(map(tuple, three_words))
wordscount = {' '.join(word): freq for word, freq in counts.items() if freq > 1}

print(wordscount)

{'show makes me': 2}

请注意,直到最后我们才使用str.join,以避免不必要的重复字符串操作。另外,tuple需要Counter转换,因为dict键必须是可哈希的。

答案 2 :(得分:0)

尝试zip(words, words[1:], words[2:])

例如:

from collections import Counter
import re

sentence = "I love TV show makes me happy, I love also comedy show makes me feel like flying"
words = re.findall(r'\w+', sentence)

three_words = [' '.join(ws) for ws in zip(words, words[1:], words[2:])]
wordscount = {w:f for w, f in Counter(three_words).most_common() if f > 1}
print( wordscount )

输出:

{'show makes me': 2}

答案 3 :(得分:0)

那又怎么样:

from collections import Counter

sentence = "I love TV show makes me happy, I love also comedy show makes me feel like flying"
words = sentence.split()
r = Counter([' '.join(words[i:i+3]) for i in range(len(words)-3)])

>>> r.most_common()[0] #get the most common 3-words
('show makes me', 2)