python中的运行时变量访问

2024-09-30 10:39:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不熟悉。在这里,我测试了在循环中使用varialbewordlist的示例。你知道吗

我需要在使用它之前手动声明它吗?或者它会被声明为运行时?你知道吗

我甚至尝试了手动声明,但它仍然是空的。你知道吗

我遵循这个例子: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

我在这里做错什么了?你知道吗


Tags: inhttp声明示例forifenglishnot
2条回答

下面是列表理解在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"]

你的第一份理解清单:

wordlist = [i for i in wordlist if not i in stopwords.words('english')]

大致相当于:

tmp_lst = []
for i in wordlist:
    if i not in stopwords.words('english'):
        tmp_lst.append(i)
wordlist = tmp_lst

当你这样读的时候,很明显wordlist必须是一个可以理解的东西,然后才能理解它。当然,什么是wordslist应该由你决定,完全取决于你想要完成的事情。。。你知道吗

相关问题 更多 >

    热门问题