Python。检查该键存在后出现错误

2024-04-20 05:43:13 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图通过键从字典中获取值时,我收到一条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

你知道为什么会这样吗?在


Tags: 代码textintest消息字典iskeys
1条回答
网友
1楼 · 发布于 2024-04-20 05:43:13

第一行显示sentiment_words,另一行显示sentiments_words(注意sentiment后面的s

sentiment_words
sentiments_words

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

^{pr2}$

或者更简单的版本(正如切普纳建议的那样):

sentiment += sentiment_words.get(test, 0)

相关问题 更多 >