gpt4 book ai didi

python - python中的运行时变量访问

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:05 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com