Skip to main content
 首页 » 编程设计

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

2024年10月25日8hnrainll

我是 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"]