当我试图通过键从字典中获取值时,我收到一条KeyError
消息。在按键获取值之前,我检查键是否存在。这是我的代码:
def getTweetSentiment(tweet_text):
print sentiment_words #{u'limited': -1, u'cut': 2, ...}
sentiment = 0
words = extractWordsFromTweet(tweet_text)
for word in words:
test = word.lower() #test is unicode
if test in sentiment_words.keys(): #Here I check that key is in a list of keys.
temp = sentiments_words[test] #!And here throws the KeyError exception
sentiment = sentiment + temp
return sentiment
你知道为什么会这样吗?在
第一行显示
sentiment_words
,另一行显示sentiments_words
(注意sentiment
后面的s
请注意,更好的解决方案可能是:
^{pr2}$或者更简单的版本(正如切普纳建议的那样):
相关问题 更多 >
编程相关推荐