NLTK中的FreqDist使用

3

我正在尝试使用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\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'

你能帮忙吗?

到目前为止,这是代码:

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)
2个回答

2
我希望至少可以提供两个想法作为答案。
首先,nltk.text.Text()方法的文档说明如下(重点在于:“)”:
“这是一个简单字符串令牌序列的封装器,旨在通过交互式控制台支持文本的初始探索。它的方法对文本的上下文进行各种分析(例如计数、协调、搭配发现)并显示结果。如果您希望编写使用这些分析的程序,则应绕过Text类,直接使用适当的分析函数或类。”
所以我不确定Text()是否是您处理此数据的方式。在我看来,使用列表就足够了。
其次,我建议您考虑一下您要求NLTK执行的计算。在确定频率分布之前删除停用词意味着您的频率会被扭曲;我不明白为什么在表格制定之前要去除停用词,而不是在事后忽略检查分布时忽略它们。(我想第二点可能比答案更好,但我认为指出比例会被扭曲很值得注意。)根据您打算使用频率分布的情况,这可能是一个问题本身,也可能不是。

dmh说得非常正确。在NLTK中不需要使用text()函数。你的corpus[]数组本身就可以用于执行FreqDist。 - Adam_G

1
错误提示说你试图使用一个列表作为哈希键。你能把它转换成元组吗?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接