Python Counter() 函数用于统计文档中出现多次的单词

问题描述 投票:0回答:3

我正在开发一个 NLP(自然语言处理)项目,其中使用了集合库中的 Python Counter() 函数。我得到以下形式的结果:

输出

Counter({'due': 23, 'support': 20, 'ATM': 16, 'come': 12, 'case': 11, 'Sallu': 10, 'tough,': 9, 'team': 8, 'evident': , 'likely': 6, 'rupee': 4, 'depreciated': 2, 'senior': 1, 'neutral': 1, 'told': 1, 'tour\n\nRussia’s': 1, 'Vladimir': 1, 'indeed,': 1, 'welcome,”': 1, 'player': 1, 'added': 1, 'Games,': 1, 'Russia': 1, 'arrest': 1, 'system.\nBut': 1, 'rate': 1, 'Tuesday': 1, 'February,': 1, 'idea': 1, 'ban': 1, 'data': 1, 'consecutive': 1, 'interbank': 1, 'man,': 1, 'involved': 1, 'aggressive': 1, 'took': 1, 'sure': 1, 'market': 1, 'custody': 1, 'gang.\nWithholding': 1, 'cricketer': 1})

问题是,我想提取计数大于 1 的单词。换句话说,我试图只获取计数大于 1 或 2 的单词。

我想在减少低频单词后使用输出制作词汇表。

PS:我有超过 100 个文档来测试我的数据,其中有近 2000 个不同的单词。

PPS:我已经尝试了一切方法来获得结果,但无法做到。我只需要一个逻辑就能实现。

python python-3.x nlp words python-collections
3个回答
6
投票

您可以迭代字典中的键、值对并将它们添加到单独的列表中。这只是你想最终生成一个列表,否则@jpp有更好的解决方案。

from collections import Counter

myStr = "This this this is really really good."
myDict = Counter(myStr.split())

myList = [k for k, v in myDict.items() if v > 1]

# ['this', 'really']

1
投票

您可以使用字典理解将您的

Counter
项目限制为计数超过 1 的单词:

from collections import Counter

c = Counter({'due': 23, 'support': 20, 'ATM': 16, 'come': 12, 'Russia': 1, 'arrest': 1})

res = Counter({k: v for k, v in c.items() if v > 1})

# Counter({'ATM': 16, 'come': 12, 'due': 23, 'support': 20})

0
投票

如果有人也想计算这两个答案,请将这两个答案结合起来。

from collections import Counter

myStr = "This this this is really really good."
c = Counter(myStr.split())

res = Counter({k: v for k, v in c.items() if v > 1})

res
© www.soinside.com 2019 - 2024. All rights reserved.