简体   繁体   中英

Give values to a sentence from a dictionary

I have 2 inpouts, several tweets in a list ['tweet 1', 'tweet 2',...] and a dictionary with {'word1': value1;'word 2': value2;...} .

Imagine the first tweet is like:

'I love eating potatoes'

And from the 500 words in the dictionary there is a value for

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

The question is: how can I search in every row if there is/are a value/s for the sentence and give it a final score?

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

I guess I have to start with this

Thank you all for the help

updated:

Hello everyone, each answer worked, but not in the way I wanted.

I need to get a print out like:

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

So how can I define score?

Thank you very much

You could use a nested list comprehension to iterate over each string in the list of tweets, add their scores if they are present in the dictionary (this returns a list of scores)

[sum(d.get(j, 0) for j in i.split()) for i in t]

Or as @yuvgin suggests, you could create a dictionary with tweets as keys and their corresponding scores:

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

If I understand your problem correctly, then below solution:

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM