我是Python新手。在这里,我正在测试循环中使用了varialbe wordlist
的示例。
使用前需要手动声明吗?或者它会被声明为运行时?
我什至尝试过手动声明,但它仍然是空的。
我正在遵循这个示例:http://www.sjwhitworth.com/sentiment-analysis-in-python-using-nltk/
如果我直接使用这个:
wordlist = [i for i in wordlist if not i in stopwords.words('english')]
wordlist = [i for i in wordlist if not i in customstopwords]
它给出错误:
wordlist = [i for i in wordlist if not i in stopwords.words('english')]
NameError: name 'wordlist' is not defined
我像这样手动声明了wordlist
wordlist = []
但在这种情况下它仍然为空:
wordlist = []
wordlist = [i for i in wordlist if not i in stopwords.words('english')]
wordlist = [i for i in wordlist if not i in customstopwords]
print wordlist
我在这里做错了什么?
最佳答案
以下是列表推导式在 Python 中的工作原理。假设你有一个列表 x
就像
x=[1,2,3,4]
并且您想使用列表理解来增加其值:
y=[element+1 for element in x]
# ^ ^ ^
#element element list on which
#to be added operations are
#in list of y performed
输出:
y=[2,3,4,5]
在您的情况下,x
(即wordlist
)为空,因此for
循环不会迭代。根据提到的link的描述 wordlist
应该是艺术家姓名的数组。
wordlist = ["Justin Timberlake", "Tay Zonday", "Rebecca Black"]
关于python - python 中的运行时变量访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25357024/