【问题标题】:How can I sum tweet value in dictionary for similar keys?如何在字典中对类似键的推文值求和?
【发布时间】:2015-12-11 02:20:59
【问题描述】:

我通过查看充满单词分数的字典来计算推文的情绪分数,并为每条推文中的每个单词计算每条推文的分数。每条推文都有一个与之关联的指定状态。因此,对于同一状态下的所有推文,我想返回一个带有 {'state', sum_of_all_sentiment_scores_per_state} 的新字典。

我是否需要使用 {'tweet', []} 创建一个新的 dict hstates,然后将 textscore 附加到每个 state_key 的列表中,然后使用 Counter 对每个状态的列表中每个 textscore 的值求和?如何将值附加到我的列表中?

# Calculate final scores of all tweets based on tweet file order
hstates = {}  #{'score', 'state'}
for item in tweet_place.items(): #tweet_place = {'tweet', 'place'}:
   text = item[0]
   state = item[1]
   words = text.split()
   textscore = 0
   for word in words:
      word = words.lower()
      try:
         textscore += scores[word] #sentiment scores dict
      except:
         pass #ignore tweet words not in sentiment scores dict
#now I have final score for each tweet
hstates[state].append(textscore)#breaks!! 
print hstates.items()

【问题讨论】:

  • textscore 甚至可以在 for 循环之外使用吗?另外,你能显示回溯吗?

标签: python dictionary twitter sum


【解决方案1】:

在这种情况下我会使用in

for word in words:
  word = words.lower()
  if word in scores:
     textscore += scores[word] #sentiment scores dict
...
if state in hstates:
    hstates[state].append(textscore)
else:
    hstates[state] = [textscore]

【讨论】:

  • 另一个选项是 value = hstates.get(state, None) 如果 value 不是 None: hstates[state] = [textscore] else: hstates[state] = [textscore]
猜你喜欢
  • 2014-02-26
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多