2016-09-16 175 views
2

以下示例创建一个anagram字典。 然而,它抛出一个TypeError: 'LazyCorpusLoader' object is not an iterator'LazyCorpusLoader'对象不可迭代

import nltk 
from nltk.corpus import words 

anagrams = nltk.defaultdict(list) 
for word in words: 
    key = ''.join(sorted(word)) 
    anagrams[key].append(word) 

print(anagrams['aeilnrt']) 

回答

5

您必须使用.words()方法words语料库对象。

具体做法是:改变

for word in words: 

for word in words.words(): 

,它应该工作。

+0

正确的答案,但OP发布的代码将在Python 2.7中工作。我认为问题在于他们试图用Python 3+来使用它。 –

+0

@Silenus好点,我没有意识到这一点。不过,我认为将代码移植到Python 3是比将环境降级到Python 2更好的选择。但这当然是有争议的。 – lenz

+0

我有同样的错误信息,这是我的代码,你可以帮助请:进口NLTK 从nltk.corpus进口名 nltk.download(“禁用词”) nltk.download(“共发现”) 进口警告 警告.filterwarnings('ignore') from nltk.corpus import stopwords def cleaning(article): one =“”.join([i for article.lower()。split()if i not in stopwords] ) 2 = “”。加入(我为我一个,如果我不是在标点符号) 3 = “”。加入(lemmatize.lemmatize(i)对于我在two.split()) 返回三个 文本=搜索.applymap(清洁)['Q2'] tex t_list = [i.split()为我在文本中] – mkheifetz