我最近有同樣的問題。
NLTK在類的python的collections
包中構建它FreqDist
。該plot()
(和tabulate()
功能),解壓即可使用的樣本如下:
samples = list(islice(self, *args))
來源:http://www.nltk.org/_modules/nltk/probability.html
我想他們正在做的這種方式,使像之間的範圍內的子序列繪製第10和第40個樣本,但它假定Counter對象(基本上是dict
)被排序。雖然有時候是這樣,但它顯然並不總是成立,正如python文檔明確指出的那樣。正確的替換在NLTK源上面一行是:
samples = [item for item, _ in self.most_common(*args)]
那正確的版本可以在最近的NLTK code on GitHub也發現。它已在NLTK 3.0.0中修復,因此請確保您沒有使用舊版本(如NLTK 3的Alpha或Beta版本)。
如果你不想改變NLTK的來源,不能更新,你可以輕鬆地適應自己的plot()
功能:
def plot_freqdist(fd, num = 0, cumulative = False, title = None):
import pylab
# Set up parameters
if num <= 0:
num = fd.B
# Get samples and frequencies
samples, freq, accu = [], [], 0
for s, f in fd.most_common(num):
accu = accu + f if cumulative else f
samples.append(s)
freq.append(accu)
# Create plot
pylab.grid(True, color = 'silver')
if title:
pylab.title(title)
pylab.plot(freq, linewidth = 2)
pylab.xticks(range(len(samples)), samples, rotation = 90)
pylab.xlabel('Samples')
pylab.ylabel('Cumulative Counts' if cumulative else 'Counts')
pylab.show()
你在哪裏定義tex1? (本書在文本上調用FreqDist()1) – duhaime 2014-09-03 21:24:56
Typo,我主要是在python命令行中運行它,並且我編寫了代碼來反映我正在運行的代碼。 – 2014-09-03 22:01:25
當您打印text1的內容時會發生什麼?你可以驗證你的text1 =你朋友的text1嗎? – duhaime 2014-09-03 22:03:32