将字典中的关键字与Python中的列表匹配 [英] Matching keywords in a dictionary to a list in Python
本文介绍了将字典中的关键字与Python中的列表匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下字典给出了单词及其值:
The following dictionary gives the word and its value:
keywords = {'alone': 1, 'amazed': 10, 'amazing': 10, 'bad': 1, 'best': 10, 'better': 7, 'excellent': 10, 'excited': 10, 'excite': 10}
在字典后的列表中,有两条推文. 对于每条推文,我们需要从中找到关键字中的哪些单词.
Following the dictionary are two tweets in a list in a list. For each tweet, we need to find which of the words from keywords are present in it.
tweets = [['work', 'needs', 'to', 'fly', 'by', '', "i'm", 'so', 'excited', 'to', 'see', 'spy', 'kids', '4', 'with', 'then', 'love', 'of', 'my', 'life', '', 'arreic'], ['today', 'is', 'going', 'to', 'be', 'the', 'greatest', 'day', 'of', 'my', 'life', 'hired', 'to', 'take', 'pictures', 'at', 'my', 'best', "friend's", 'gparents', '50th', 'anniversary', '60', 'old', 'people', 'woo']]
目标是找到在每个推文行中找到的关键字值总和.
The target is to find the sum of the keyword values found in each tweet line.
创建的代码需要循环,因为有2条以上的推文. 我不知道如何执行此过程.
The code created needs to be a loop because there are more than 2 tweets. I do not understand how I should execute this process.
感谢您的见识!
推荐答案
尝试一下:
keywords = {'alone': 1, 'amazed': 10, 'amazing': 10, 'bad': 1, 'best': 10, 'better': 7, 'excellent': 10, 'excited': 10, 'excite': 10}
tweets = [['work', 'needs', 'to', 'fly', 'by', '', "i'm", 'so', 'excited', 'to', 'see', 'spy', 'kids', '4', 'with', 'then', 'love', 'of', 'my', 'life', '', 'arreic'], ['today', 'is', 'going', 'to', 'be', 'the', 'greatest', 'day', 'of', 'my', 'life', 'hired', 'to', 'take', 'pictures', 'at', 'my', 'best', "friend's", 'gparents', '50th', 'anniversary', '60', 'old', 'people', 'woo']]
total = 0
for i in keywords:
for j in tweets:
if i in j:
occourance = j.count(i)
print('keyword=', i)
total += keywords[i]*occourance
print('sum is: ', total)
output:
keyword= best
keyword= excited
sum is: 20
这篇关于将字典中的关键字与Python中的列表匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文