【问题标题】:Aggregate results from for loop in python聚合python中for循环的结果
【发布时间】:2016-02-01 20:16:21
【问题描述】:

我正在用 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。谢谢

【问题讨论】:

    标签: python for-loop sentiment-analysis


    【解决方案1】:

    累积这些值并在循环结束后打印它们:

    # ...
    
    finalScore = 0 # final score
    for word in words:
    
        if word in scores:
            result = scores[word]
            resscore.append(result)
    
            finalScore += sum(resscore)
    
    print(str(finalScore))
    
    # ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 2018-09-06
      • 1970-01-01
      • 2017-12-24
      • 2013-01-06
      • 2018-12-23
      • 2017-09-30
      相关资源
      最近更新 更多