Python:如何计算NLTK语料库中使用最频繁的前X个单词?

10

我不确定自己是否正确理解了Python中FreqDist函数的工作方式。因为我在按照教程学习,根据教程所说,下面的代码会为给定的单词列表构建一个频率分布,并计算出使用频率最高的x个单词。(在下面的示例中,corpus是一个NLTK语料库,file是该语料库中某个文件的文件名)

words = corpus.words('file.txt')
fd_words = nltk.FreqDist(word.lower() for word in words)
fd_words.items()[:x]

然而,当我在Python上执行以下命令时,它似乎表示相反:

However, when I go through the following commands on Python, it seems to suggest otherwise:

>>> from nltk import *
>>> fdist = FreqDist(['hi','my','name','is','my','name'])
>>> fdist
FreqDist({'my': 2, 'name':2, 'is':1, 'hi':1}
>>> fdist.items()
[('is',1),('hi',1),('my',2),('name',2)]
>>> fdist.items[:2]
[('is',1),('hi',1)]

fdist.items()[:x] 方法实际上返回的是出现频率最低的 x 个单词吗?

有人能告诉我是否我做错了什么,或者错误在我正在跟随的教程中吗?


1
你可以从这里的答案中获得一些帮助(https://dev59.com/PGAg5IYBdhLWcg3w5ucd)。本质上,`.items()`使用的是stdlib实现,因此它不会排序。如果你想要最常见的x个单词,请使用:`fdist.most_common(x)`。 - MrAlexBailey
请注意,NLTK 3中FreqDist的排序行为已更改。这可能会解释混淆的原因。另外:使用fd_words.most_common()而不带参数,以按降序获取所有内容。 - alexis
或者你可以像这里展示的那样做一些漂亮的事情 https://plot.ly/python/table/ - Dexter
1个回答

20

默认情况下,FreqDist不是排序的。我想你正在寻找most_common方法:

from nltk import FreqDist
fdist = FreqDist(['hi','my','name','is','my','name'])
fdist.most_common(2)

返回:

[('my', 2), ('name', 2)]

3
Counter('hi','my','name','is','my','name']).most_common()也能做到相同的效果。;P. 参见此链接:https://dev59.com/yZLea4cB1Zd3GeqP5a1P#34606637 - alvas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接