Counter() 是嵌套列表中的三次计数项

Counter() is triple counting items in nested list

我想搜索 a text file 特定关键字,然后创建一个包含每个关键字的绝对计数和相对频率的字典。我在一个嵌套循环中使用 Counter(),它应该在我的列表中查找每个关键字,然后计算每个关键字在文档中出现的频率。但是,虽然 Counter 正确地计算了每个关键字,但它随后将此计数乘以关键字总数。我想我设置的嵌套循环不正确。

from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk import FreqDist
import io
from collections import Counter


with io.open('copy.txt','r', encoding='utf-8') as tempFile:
    rawText =  tempFile.read()
    rawText = rawText.lower()

cnt = Counter()

tokens = word_tokenize(rawText)

keywords = ['kingdom', 'phylum', 'class', 'status']

for keyword in keywords:
    for keyword in tokens:
        cnt[keyword] += 1

for keyword in keywords:
    d = {'Keyword': keyword, 'Count': cnt[keyword], 'Frequency':cnt[keyword]/float(len(tokens))}
    print(d)

我应该看到:

{'Count': 2, 'Frequency': 0.000882223202470225, 'Keyword': 'kingdom'}
{'Count': 6, 'Frequency': 0.002646669607410675, 'Keyword': 'phylum'}
{'Count': 14, 'Frequency': 0.0061755624172915745, 'Keyword': 'class'}
{'Count': 2, 'Frequency': 0.000882223202470225, 'Keyword': 'status'}

但是我看到了:

{'Count': 8, 'Frequency': 0.000882223202470225, 'Keyword': 'kingdom'}
{'Count': 24, 'Frequency': 0.002646669607410675, 'Keyword': 'phylum'}
{'Count': 56, 'Frequency': 0.0061755624172915745, 'Keyword': 'class'}
{'Count': 8, 'Frequency': 0.000882223202470225, 'Keyword': 'status'}

问题就在这里

for keyword in keywords:
    for keyword in tokens:
        cnt[keyword] += 1

您一次又一次地计算关键字的长度。

如果你能post你的rawtext,我也许能提供完整的解决方案。

我想我的 for 循环顺序颠倒了。这似乎有效:

for token in tokens:
    if token in keywords:
        cnt[token] += 1