微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从对应于特定键的字典中获取特定值,并将该值添加到变量中?

如何解决如何从对应于特定键的字典中获取特定值,并将该值添加到变量中?

我在使用python字典时遇到麻烦。我有一本字典,看起来像这样,其中keyword ='alone'和value ='1'(同样对于字典中的其余元素):

{'alone': '1','amazed' : '10','amazing' : '10','bad': '2','best': '10','better' : '9','excellent' : '10','excited' : '10','excite' : '10','excites' : '10','exciting' : '10','glad' : '8','god' : '5','good' : '6','great' : '7','hate' : '1','hurt' : '1','positive' : '6','thanks' : '4','tired' : '3'}

我必须浏览一个tweets的文本文件,查看给定tweet中的任何单词是否与字典中的任何单词匹配,然后将相应的整数值添加到变量sum_value中。

我的代码现在看起来像这样,但是我不知道是否在变量sum_value中添加了正确的值。

        sum_value = 0
        if word in dictionary:
                value = dictionary[keyword]
                sum_value += dictionary[value]
        else:
                continue

基本上,如果一条推文为“我感到孤独”,则程序应感觉到关键字匹配,并将关键字“ alone”的相应值添加到sum_value。我不知道该怎么办...有人可以帮我吗?

谢谢!

解决方法

您可以使用dictionary['key']

从字典键中检索值。
mydict={'alone': '1','amazed' : '10','amazing' : '10','bad': '2','best': '10','better' : '9','excellent' : '10','excited' : '10','excite' : '10','excites' : '10','exciting' : '10','glad' : '8','god' : '5','good' : '6','great' : '7','hate' : '1','hurt' : '1','positive' : '6','thanks' : '4','tired' : '3'}

sum_value = 0 
word ='alone'
if word in mydict:    
    value = mydict[word]
    sum_value+= int(value)
    print(sum_value)
    
,

您可能也需要for循环。例如,您的代码可能如下所示:

tweet = input("Tweet: ")

sum_value = 0

words = tweet.split()
print(words)

dictionary_words=dictionary.keys()

for i in dictionary_words:
    print(i)

for word in words:
    for i in dictionary:
        if word == i:
            sum_value = sum_value + int(dictionary[i])
    else:
        continue
        
print(sum_value)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。