我有 2 个输入,列表中有几条推文 ['tweet 1', 'tweet 2',...]
和一个带有 {'word1': value1;' 的字典单词 2': value2;...}
.
想象第一条推文是这样的:
'I love eating potatoes'
字典中的 500 个单词有一个值
{...;'love': 3;...;'potatoes': -1;...}.
问题是:如何在每一行中搜索该句子是否有一个值并给出最终分数?
tweet=[]
values={}
for list in tweet:
divided_tweet=list.split()
我想我必须从这个开始
谢谢大家的帮助
更新:
大家好, 每个答案都有效,但不是我想要的方式。
我需要打印如下:
print(str(tweet)+"// The total score is: "str(score))
那么我该如何定义分数呢?
非常感谢
最佳答案
您可以使用嵌套的列表理解来迭代推文列表中的每个字符串,如果它们存在于字典中,则添加它们的分数(这将返回分数列表)
[sum(d.get(j, 0) for j in i.split()) for i in t]
或者正如 @yuvgin 所建议的,您可以创建一个以推文为键及其相应分数的字典:
{i : sum(d.get(j, 0) for j in i.split()) for i in t}
示例
t = ['I love eating potatoes', 'second tweet']
d = {'love': 3,'potatoes': -1}
{i : sum(d.get(j, 0) for j in i.split()) for i in t}
# {'I love eating potatoes': 2, 'second tweet': 0}
关于python - 为字典中的句子赋予值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54505301/