2016-02-01 103 views
1

我正在python中进行情感分析。清理推文后,我坚持要获得每条推文的最终情绪分数。我得到的价值,但无法将每条推文的总分作为一个分数。下面的代码Python中for循环的聚合结果

scores = {} # initialize an empty dictionary 
for line in sent_file: 
    term, score = line.split("\t") 
    scores[term] = int(score) # Convert the score to an integer. 



for line in tweet_file: 
     #convert the line from file into a json object 
    mystr = json.loads(line) 
    #check the language is english, if "lang" is among the keys 
    if 'lang' in mystr.keys() and mystr["lang"]=='en': 
      #if "text" is not among the keys, there's no tweet to read, skip it 
     if 'text' in mystr.keys(): 
      print mystr['text'] 
      resscore=[] 
      result = 0 
      #split the tweet into a list of words 
      words = mystr["text"].split() 
      #print type(words) 
      for word in words: 

       if word in scores: 
        result = scores[word] 
        resscore.append(result) 

        print str(sum(resscore)) 


       else: 
        result+=0 

我得到的输出是一样

If nothing is as you'd imagine it to be then you may as well start imaging some mad stuff like dragons playing chess on a… 
-3 
-1 

但我想在这种情况下-3这些值,-1进行汇总,给出该鸣叫即-4最终得分,由于

回答

2

积累与循环结束后&打印出来的值:

# ... 

finalScore = 0 # final score 
for word in words: 

    if word in scores: 
     result = scores[word] 
     resscore.append(result) 

     finalScore += sum(resscore) 

print(str(finalScore)) 

# ... 
+0

感谢穆罕默德 – suri

+0

@suri欢迎您 –