2016-09-16 294 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