【问题标题】:Give values to a sentence from a dictionary给字典中的句子赋值
【发布时间】:2019-06-27 13:17:23
【问题描述】:

我有 2 个输入,列表中有几条推文 ['tweet 1', 'tweet 2',...] 和一个带有 {'word1': value1;'word 2': value2;...} 的字典。

想象第一条推文是这样的:

“我喜欢吃土豆”

从字典中的 500 个单词中,有一个值

{...;'love': 3;...;'potatoes': -1;...}.

问题是:如果句子有值,我如何在每一行中搜索并给出最终分数?

tweet=[]
values={}
    for list in tweet:
        divided_tweet=list.split()

我想我必须从这个开始

谢谢大家的帮助

更新:

大家好, 每个答案都有效,但不是我想要的方式。

我需要打印如下:

print(str(tweet)+"// The total score is: "str(score))

那么我该如何定义分数呢?

非常感谢

【问题讨论】:

  • 如果一个单词不存在,是否应该返回0?
  • 真的是'potatoes': -1吗?或'potatoes': 1
  • sum(dictionary.get(word, 0) for word in divided_tweet)。注意:不要使用 python 的内置类型或函数作为变量名,例如list.
  • @SwadhikarC 是的,有一些正面和负面的价值
  • @aws_apprentice 是的,应该

标签: python list dictionary for-loop if-statement


【解决方案1】:

您可以使用嵌套的 list comprehension 来遍历推文列表中的每个字符串,如果它们存在于字典中,则添加它们的分数(这将返回一个分数列表)

[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}

【讨论】:

  • 我会考虑更改您的解决方案以输出带有相应推文和分数的字典。会更容易使用......显然会想到一个dict理解......
  • 所以你会将分数添加到字典中,其中键是实际的推文?
  • 是的,与列表相比,跟踪每条推文的得分似乎更合乎逻辑。
  • 是的,不错的建议已将其添加到答案中
  • 我更新了问题,如果你能帮忙的话:)
【解决方案2】:

如果我正确理解你的问题,那么下面的解决方案:

stream = ['I love tweet 1', 'I loves kt',] # Your input steam if tweets

kv = {'love': 1,'tweet': 2} # Your key value matching pair

print ([x for x in stream if any(j in kv for j in x.split())]) # o/p prints only those stream where atleast a single match is present in stream kv.

# output: ['I love tweet 1']

【讨论】:

    猜你喜欢
    • 2019-05-14
    • 2016-10-24
    • 2018-05-29
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 2021-12-17
    • 2011-07-23
    相关资源
    最近更新 更多