聚合来自python中for循环的结果

时间:2016-02-01 12:13:16

标签: python for-loop sentiment-analysis

我在python中进行情绪分析。在清理完使用的推文之后,我不得不按每条推文获得最终的情绪评分。我正在获取值,但无法将每个推文的一个分数聚合在一起。这是代码

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。感谢

1 个答案:

答案 0 :(得分: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))

# ...