【问题标题】:Python: How to compute the top X most frequently used words in an NLTK corpus? [duplicate]Python:如何计算 NLTK 语料库中最常用的 X 个单词? [复制]
【发布时间】:2016-01-29 22:32:50
【问题描述】:

我不确定我是否正确理解了 FreqDist 函数在 Python 上的工作原理。当我学习教程时,我相信以下代码为给定的单词列表构建频率分布并计算前 x 个常用单词。 (在下面的示例中,让 corpus 为 NLTK 语料库,file 为该语料库中文件的文件名)

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

但是,当我在 Python 上执行以下命令时,似乎另有建议:

>>> 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 个最不常用的词?

谁能告诉我是我做错了什么,或者错误出在我正在学习的教程中吗?

【问题讨论】:

  • 您可能会得到一些帮助from answers here。本质上.items() 使用的是stdlib 实现,所以它没有排序。如果您想要 x 最常用的单词,请使用:fdist.most_common(x)
  • 请注意,FreqDist 的排序行为在 NLTK 3 中发生了变化。这可以解释这种混淆。另外:使用fd_words.most_common(),不带参数,按频率降序获取所有内容。
  • 或者你可以做一些漂亮的事情,如下所示plot.ly/python/table

标签: python nltk


【解决方案1】:

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

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

返回:

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

【讨论】:

猜你喜欢
  • 2016-06-19
  • 2020-03-24
  • 1970-01-01
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
相关资源
最近更新 更多