NameError:未定义名称'word',python

问题描述 投票:0回答:1

我正在尝试使用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的新手。

python-3.x nltk
1个回答
0
投票

您必须翻转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.
© www.soinside.com 2019 - 2024. All rights reserved.