【发布时间】:2014-02-08 20:58:52
【问题描述】:
我有 wdict 作为字典,我想将所有唯一的单词添加到其中,这些单词是从存储在 path 的文本文件中扫描并由 CleanDoc() 转换为单词列表的。 我收到错误 AttributeError: 'dict' object has no attribute 'union'。我该怎么办?
import collections
import os.path
import glob
import nltk
wdict = {}
path = "C://Python27//Corpus Files//*.*"
#this function cleans up a doc (removes stopwords etc)
def cleanDoc(doc):
stopset = set(nltk.corpus.stopwords.words('english'))
stemmer = nltk.PorterStemmer()
tokens = nltk.WordPunctTokenizer().tokenize(doc)
clean = [token.lower() for token in tokens if token.lower() not in stopset and len(token) > 3 and token.isalpha() and not 'reuter']
final = [stemmer.stem(word) for word in clean]
return final
for text in glob.glob(path):
f = open(text)
data= f.read()
words = cleanDoc(data)
wdict = wdict.union(words)
print wdict
【问题讨论】:
-
看看dict API。
dict没有union方法。 -
请注意(一旦将其设为
set),您将在尝试分配给global时获得UnboundLocalError,而无需声明它。
标签: python dictionary union corpus