2016-01-29 35 views
3

我不確定我是否正確理解FreqDist函數在Python上的工作原理。正如我正在學習一個教程,我被引導認爲下面的代碼爲給定的單詞列表構造了一個頻率分佈,並計算了最常用的單詞x。 (在下面就讓語料庫的例子是NLTK語料庫和文件是文件的在語料庫中的文件名)Python:如何計算NLTK語料庫中最常用的最常用詞彙?

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最不常用的單詞嗎?

有人可以告訴我,如果我做錯了什麼,或者如果錯誤在於我所遵循的教程?

+1

你可能會得到一些幫助[從這裏的答案(http://stackoverflow.com/questions/23042699/freqdist-in -nltk-未排序輸出)。基本上'.items()'使用的是stdlib實現,所以它沒有排序。如果你想使用x最常用的單詞:'fdist.most_common(x)' – Jkdc

+0

請注意,FreqDist的排序行爲在NLTK 3中已經改變。這可能解釋了混淆。另外:使用'fd_words.most_common()',不帶參數,以降序的順序獲取所有內容。 – alexis

+0

或者你可以做一些漂亮的事情,如下所示https://plot.ly/python/table/ – Dexter

回答

6

默認情況下,FreqDist未排序。我認爲你正在尋找most_common方法:

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

返回:

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

'Counter('hi','my','name','is','my','name'] ).most_common()'也會這樣做; P。看到這個:http://stackoverflow.com/questions/34603922/difference-between-pythons-collections-counter-and-nltk-probability-freqdist/34606637#34606637 – alvas

相關問題