我正在尝试使用nltk创建一个聊天机器人。在这里,我有一个列表,正在使用LancasterStemmer转换为小写字母及其根词。我收到此错误:
NameError:未定义名称'word'。
如何使此代码更好?
words = [stemmer.stem(w.lower()) for w in word.split() for word in words if word not in ignore]
words = sorted(list(set(words)))
我是python的新手。
您必须翻转for
循环,从word
循环开始,然后是w
循环:
words = [stemmer.stem(w.lower()) for word in words for w in word.split() if word not in ignore]
这类似于普通的for
循环,您不能有此循环:
for w in word.split(): # << what is `word` here? it's not defined yet.
for word in words:
相反,您应该拥有这个:
for word in words:
for w in word.split(): # << `word` is defined here from the outer loop.