Skip to main content
 首页 » 编程设计

python之NLTK FreqDist,绘制归一化计数

2024年10月17日7bhlsheji

在 NLTK 中,您可以轻松地计算文本中单词的计数,例如,通过执行以下操作

from nltk.probability import FreqDist 
fd = FreqDist([word for word in text.split()]) 

其中文本是一个字符串。 现在,您可以将分布绘制为

fd.plot() 

这将为您提供一个漂亮的线图,其中包含每个单词的计数。在docs没有提到绘制实际频率的方法,您可以在 fd.freq(x) 中看到。

有什么直接的方法可以绘制归一化计数,无需将数据放入其他数据结构,单独进行归一化和绘图?

请您参考如下方法:

您可以使用 fd[word]/total 更新 fd[word]

from nltk.probability import FreqDist 
 
text = "This is an example . This is test . example is for freq dist ." 
fd = FreqDist([word for word in text.split()]) 
 
total = fd.N() 
for word in fd: 
    fd[word] /= float(total) 
 
fd.plot() 

注意:您将丢失原始的 FreqDist 值。