如何从字典中获取单词列表的值?

2024-04-20 06:57:50 发布

您现在位置:Python中文网/ 问答频道 /正文

(对不起,如果我写错了帖子或者在代码中犯了一些严重的错误,这是我在这的第一周)

我有一本字典,通过以下代码获得:

import json
sentimientos=open("Sentimientos.txt")
valores={}
for linea in sentimientos:
    termino, valor=linea.split("\t")
    valores[termino]=(int(valor)):
print(valores.items())

看起来是这样的:

dict_items([('abandon', -2), ('abandoned', -2), ('abandons', -2), ('abducted', -2)...

但用了很多词

然后我有一个单词列表(使用method.split(“”)从tweets中获取), 我需要检查第二张单子上的每一个单词,如果字典上有这个单词,如果有,把它的值放在字典里

我从列表中获得单词的代码是:

tw = open("salida_tweets.txt")
tweets = []
for linea in tw:
    clean_tweet = json.loads(linea)
    tweets.append(clean_tweet["text"])
    words = [tweet.split(" ") for tweet in tweets]
print(words)

我有这样的想法:

[['@Brenamae_', 'I', 'WHALE', 'SLAP', 'YOUR', 'FIN', 'AND', 'TELL', 'YOU', 'ONE', 'LAST', 'TIME:'...

但是,像以前一样,用了很多话

正如我所说,我需要做一个列表,对于每条tweet,打印字典中每个tweet单词的值(如果tweet有超过1个单词,则为单词的总和)。你知道吗

我很难做到这一点。你知道吗

“谢谢大家!你知道吗

警察:我试过的是:

import json
sentimientos=open("Sentimientos.txt")
valores={}
for linea in sentimientos:
    termino, valor=linea.split("\t")
    valores[termino]=(int(valor)):
tw = open("salida_tweets.txt")
tweets = []
for linea in tw:
    clean_tweet = json.loads(linea)
    tweets.append(clean_tweet["text"])
    words = [tweet.split(" ") for tweet in tweets]
    if words in valores:
    valorestweet.append(sum(valores.get(words) for valor in valores)

我得到的是

<ipython-input-68-30a0230d33a7> in <module>()
    19         tweets.append(clean_tweet["text"])
    20         words = [tweet.split(" ") for tweet in tweets] 
    ---> 21         if words in valores:
    22             valorestweet.append(sum(valores.get(words) for valor in valores))
    23 print(valorestweet)

TypeError:无法处理的类型:“list”

第22行和第23行用红色标注


Tags: incleanjsonfor字典单词tweetsvalor
1条回答
网友
1楼 · 发布于 2024-04-20 06:57:50

我真的不确定我是否做对了,但假设你有这样的意见:

tweet0 = "Hello, I am groot"
tweet1 = "My name is red"
tweets = [tweet0, tweet1]

用这样的措辞:

dict = {'Hello': 1, 'I': -2, 'Yellow': -2, 'blue': -5, 'red': 4}

那么预期的输出将是这样一个列表:

[sum of the words value for tweet 1, sum of the world values for tweet 2]

如果这真的是您想要的,那么下面的代码将执行以下操作:

dict = {'Hello': 1, 'I': -2, 'Yellow': -2, 'blue': -5, 'red': 4}

tweet0 = "Hello, I am groot"
tweet1 = "My name is red"
tweets = [tweet0, tweet1]

words = [tweet.split(" ") for tweet in tweets]

Results = list()

for i in range(len(tweets)):
    # words[i] are the words from the tweet i
    value = 0
    for word in words[i]:
        if word in dict:
            value += dict[word]
    Results.append(value)

print (Results)

此示例的输出为:

[-2, 4]

-2是因为tweet0中只有“I”,4是因为tweet1中有“red”。你知道吗

正如你所注意到的,既然“Hello”后面有一个“,”,它就不考虑这个词了。这可以用另一个in语句来解决,我们还可以将.lower()方法添加到str中,以避免大写字母出现任何问题。你知道吗

因为我不确定你想要什么,我只是做了这个概念证明。如果你能给我们明确的例子,我可以改进它。你知道吗

相关问题 更多 >