从包含单词及其情绪的文本文件中,我尝试使用 python 仅打印表示悲伤情绪的单词。有人请帮助我

From a text file consisting words and their emotions , i tried to print only the words for sad emotions using python. Someone please help me

import re
word ="sad"

sadwords=[]
with open('emotions.txt','r') as file :
    for line in file :
        if word in file:
            sadwords.append(word)

print(sadwords)

从包含单词及其情绪的文本文件中,我尝试使用 python 仅打印表示悲伤情绪的单词。有人请帮助我。 This is the emotion text file

请注意,在示例中,sadwords.append(word) 将单词 'sad' 添加到每个匹配项的列表中,而不是情感。

尝试:

word ="sad"

sadwords = []
with open('emotions.txt','r') as file :
    for line in file :
        if word in line:
            sadwords.append(line.split(':')[0])

print(sadwords)

如果您想去除情绪周围的引号,则可以使用正则表达式来仅提取情绪。

import re
sadwords = []
with open('emotions.txt','r') as file :
    for line in file :
        m = re.search("'(.*?)': 'sad'", line)
        if m:
            sadwords.append(m.group(1))
print(sadwords)

输出:

['afflicted', 'agonized', 'anguished', ...]

两个小错误:

word = "sad"

sadwords=[]

with open('emotions.txt','r') as file :
    for line in file :
        # check if in line, not in file.
        if word in line:
            # append the line not the word.
            sadwords.append(line.split(":")[0].split("'")[1])
            #this gets the word and removes the ''.