蟒蛇。检查该密钥后存在KeyError

时间:2014-11-02 12:30:47

标签: python python-2.7

当我尝试按键从字典中获取值时,我收到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

任何想法为什么会发生?

1 个答案:

答案 0 :(得分:2)

第一行显示sentiment_words,其他显示sentiments_words(请注意s后的sentiment

sentiment_words
sentiments_words

请注意,更好的解决方案可能是:

word = sentiment_words.get(test)
if word is not None:  # the `is not None` part is only required if '' could occur as a word
    sentiment += word

或者这个案例的简单版本(正如Chepner建议的那样):

sentiment += sentiment_words.get(test, 0)