2

I am new to python. Here I was testing on example where varialbe wordlist has been used in loop.

Do I need to declare it manually before using it? or it would get declared runtime?

I even tried with manual declaration but then it remains empty.

I am following this example: http://www.sjwhitworth.com/sentiment-analysis-in-python-using-nltk/

If I directly use this:

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

it gives error:

wordlist = [i for i in wordlist if not i in stopwords.words('english')]
NameError: name 'wordlist' is not defined

I manually declared wordlist like this

wordlist = []

but then it remain empty in this case:

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

What wrong I am doing here?

2
  • 2
    You need to set wordlist before you use it. If it's not set, it gives the error you have. If you set it to an empty list, it will remain empty, because the list comprehensions don't add anything to the list Commented Aug 18, 2014 at 5:49
  • @hlt: thanks dude. can you please tell me what should be assigned to wordlist? looking at link. Much appreciable Commented Aug 18, 2014 at 5:54

2 Answers 2

1

Here's how list comprehensions work in python. Say you have a list x like

x=[1,2,3,4]

and you would like to increment its values using list comprehension:

y=[element+1 for element in x]
#   ^               ^       ^
#element         element    list on which
#to be added                operations are
#in list of y               performed

This outputs:

y=[2,3,4,5]

In your case x(i.e., wordlist) is empty so, the for loop does not iterate. According to the mentioned link's description wordlist should be an array of artist names.

wordlist = ["Justin Timberlake", "Tay Zonday", "Rebecca Black"]
Sign up to request clarification or add additional context in comments.

Comments

1

Your first list comprehension:

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

is roughly equivalent to:

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

When you read it this way, it's clear that wordlist must be something iterable before you ever get to that statement. Of course, what wordslist should be is up to you and is completely dependent on what you're trying to accomplish...

2 Comments

thanks dear for answer. I replace with your above code but still it gives same error at line two in your code
thanks dude, I sorted out. just filled wordlist wordlist = getwordfeatures(getwords(tweets))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.