如何计算排序列表中单词的频率?

问题描述 投票:-2回答:1
npl = []
for i in df2['Review']:
    npl.extend(tb(i).noun_phrases)

这是我用来生成列表的代码,它很长。

['omg',
 'populus scramble',
 'coffee',
 'hack',
 'snagged',
 'burpple',
 'ice cream melts',
 'sweet prize 😋',
 ...]

基本上,我如何开发一个代码来循环列表来计算单词的频率并显示单词呢?像Counter这样的东西。我花了几个小时浏览这个网站,试图找到一个适合我的代码,但无济于事。

npl.count('coffee')    

使用上面的代码可以工作,但它只适用于一个单词

预期的输出是这样的:

 {'coffee', '45'
  'snagged', '23'
  'ice cream melts', '13'}
python python-3.x
1个回答
1
投票

您可以在数据框上使用Counter from Library集合,如下所示:

word_counter = Counter()
df2['Review'].str.split(" ").apply(word_counter.update)

但是,当您有一个列表时,您可以直接将其应用于列表:

word_counter = Counter("your list")

如果你愿意,你可以循环索引并删除一些停用词。你也可以通过word_counter.most_common(10)看到最常见的

但要注意,由于房屋或房屋等多处写作,您的结果将不会完美。最好的方法是首先标记化并应用词干分析器。

Edit1

如果你想要一个最常见的字典,你可以这样做:

dict(word_counter .most_common(10))

这是我的片段:

from collections import Counter

inp = list("abcaddabcabadbcabdabdcbaziyutoigkfdshjkbvaoiuhgbgjkvd^giohdfb")
word_counter = Counter(inp)

dict(word_counter.most_common(4)) => {'a': 9, 'b': 10, 'c': 4, 'd': 8}
© www.soinside.com 2019 - 2024. All rights reserved.