Python 使用NLTK的FreqDist
我正在尝试使用Python获取一组文档的频率分布。我的代码因某种原因无法工作,并产生以下错误:Python 使用NLTK的FreqDist,python,frequency,nltk,frequency-distribution,Python,Frequency,Nltk,Frequency Distribution,我正在尝试使用Python获取一组文档的频率分布。我的代码因某种原因无法工作,并产生以下错误: Traceback (most recent call last): File "C:\Documents and Settings\aschein\Desktop\freqdist", line 32, in <module> fd = FreqDist(corpus_text) File "C:\Python26\lib\site-packages\nltk\proba
Traceback (most recent call last):
File "C:\Documents and Settings\aschein\Desktop\freqdist", line 32, in <module>
fd = FreqDist(corpus_text)
File "C:\Python26\lib\site-packages\nltk\probability.py", line 104, in __init__
self.update(samples)
File "C:\Python26\lib\site-packages\nltk\probability.py", line 472, in update
self.inc(sample, count=count)
File "C:\Python26\lib\site-packages\nltk\probability.py", line 120, in inc
self[sample] = self.get(sample,0) + count
TypeError: unhashable type: 'list'
错误表示您试图使用列表作为哈希键。你能把它转换成一个元组吗?我希望这两个想法至少能为答案做出贡献 首先,nltk.text.text()方法的文档说明(重点): 围绕简单(字符串)标记序列的包装器,用于支持文本的初始探索(通过交互式控制台)。它的方法对文本的上下文进行各种分析(例如,计数、协和、搭配发现),并显示结果如果您希望编写一个利用这些分析的程序,那么您应该绕过文本类,直接使用适当的分析函数或类。 所以我不确定Text()是否是处理这些数据的方式。在我看来,你可以使用列表
其次,我要提醒您考虑一下您要求NLTK在这里执行的计算。在确定频率分布之前删除停止词意味着你的频率将被扭曲;我不明白为什么在制表之前删除stopwords,而不是在事后检查分布时忽略它。(我想这第二点会比部分答案提出更好的查询/评论,但我觉得值得指出的是,比例会有偏差。)根据您打算使用频率分布的目的,这本身可能是一个问题,也可能不是一个问题。dmh完全正确。无需在NLTK中使用
text()
函数。您的corpus[]
数组可以执行FreqDist。
import os
import nltk
from nltk.probability import FreqDist
#The stop=words list
stopwords_doc = open("C:\\Documents and Settings\\aschein\\My Documents\\stopwords.txt").read()
stopwords_list = stopwords_doc.split()
stopwords = nltk.Text(stopwords_list)
corpus = []
#Directory of documents
directory = "C:\\Documents and Settings\\aschein\\My Documents\\comments"
listing = os.listdir(directory)
#Append all documents in directory into a single 'document' (list)
for doc in listing:
doc_name = "C:\\Documents and Settings\\aschein\\My Documents\\comments\\" + doc
input = open(doc_name).read()
input = input.split()
corpus.append(input)
#Turn list into Text form for NLTK
corpus_text = nltk.Text(corpus)
#Remove stop-words
for w in corpus_text:
if w in stopwords:
corpus_text.remove(w)
fd = FreqDist(corpus_text)