fscore
fscore

Reputation: 2619

loop not incrementing in list python

I taking a file at standard input which looks like

12    125      "neg"       Won the match #getin . P

and then doing word analysis of the sentence.

I dont know why but the loop is not getting incremented in the function "unigrams_nrc". i value is still 0

Here is the code:

def unigrams_nrc(file):
      for line in file:
      (term,score,numPos,numNeg) = re.split("\t", line.strip())
      print sentence[i] #=> prints all 0's i does not increment
      if re.match(sentence[i],term.lower()):
         wordanalysis["unigram"] = found
      else:
         found = False
      if found:
         wordanalysis["trail_unigram"] = found if re.match(sentence[(len(sentence)-1)],term.lower()) else not(found)
         wordanalysis["lead_unigram"] = found  if re.match(sentence[0],term.lower()) else not(found)
         wordanalysis["nonzero_sscore"] = float(score) if (float(score) != 0) else 0             
         wordanalysis["sscore>0"] = (float(score) > 0)
         wordanalysis["sscore"] = (float(score) != 0)

      if re.match(tweet[len(sentence)-1],term.lower()):
         wordanalysis["sscore !=0 last token"] = (float(score) != 0)


for line in sys.stdin:
    #12    125    "neg"       Won the match #getin . P
   (tweetid,num,senti,tweets) = re.split("\t+",line.strip())
   sentence = re.split("\s+", tweets.strip())
   for i in range(0,len(sentence)):
      unigrams_nrc(file)

Even if I pass i in parameter to the function.. still no change.

Upvotes: 1

Views: 2663

Answers (2)

Mailerdaimon
Mailerdaimon

Reputation: 6080

You want to do something like this

def foo1():
    print something[i]

def foo0():
    for i in range(0,number):
        foo1(somethingElse)

This is not possible!
How should foo1 know the value of i and sentence? You have to pass the values if you want to use them.

def foo1(something,i):
    print something[i]

def foo0():
    for i in range(0,number):
        foo1(something,i)

Upvotes: 0

Janne Karila
Janne Karila

Reputation: 25197

The indentation is not correct, but assuming it supposed to be like in your other question, print sentence[i] is inside the for line in file: loop. Since i is not incremented inside the loop, you see the same thing printed many times.

When you call unigrams_nrc the second time, there are no more lines to read in file, so the loop executes zero times. To read the file again you need to close and open it, or seek to the beginning. Though, reading the data into eg. a dictionary, or even just a list, would speed up your program.

A quick fix would be to add file = file.readlines() after opening file; the rest of your code should work as is then.

Upvotes: 2

Related Questions