分析一个文件中的单词并检查它们是否在另一个文件的每一行中时遇到麻烦 &... python

trouble with analyzing words in one file and checking if they are in each line of another file &… in python

所以,我正在尝试搜索 file2.txt 中的每一行是否包含 file1.txt 1 中的任何单词。因此,例如:

文件 1:

love,10
like,5
best,10
hate,1
lol,10
better,10
worst,1

file 2 : 一堆句子我想看看它是否包含任何file1(超过200行)

我有一种方法可以在我的程序中使用我自己的文件来执行此操作,它可以工作,但它将总值添加到一个大列表中(比如如果整个文件说爱 43 次,那么 Love:43 , 但我正在为每一行寻找单独的列表.. 所以如果一行包含 love 4 次和另外 5 次然后程序将指示这一点.. **具体来说, 我想要做的是总计文件每一行中的关键字(所以如果一行包含 4 个关键字,那么该行的总数是 4,以及与关键字关联的值(所以你看到在我的示例文件中如何有一个与关键字关联的值?如果文件中的一行是:Hi I love my boyfriend but I like my bestfriend lol 那么这将是 {Love: 1, like: , lol:1}(keywords = 3, Total = 25(总数来自列表中与它们关联的值)

如果第二行只是

I hate my life. It is the worst day ever!

那么这就是 {hate: 1, worst: 1}(keywords = 2, total = 2

我有这个,它可以工作,但是有没有办法修改它而不是像这样打印一大行:

{'please': 24, 'worst': 40, 'regrets': 1, 'hate': 70,... etc,} it simply adds the total number of keywords per line and the values associated with them?

wordcount = {}
with open('mainWords.txt', 'r') as f1, open('sentences.txt', 'r') as f2:
    words = f1.read().split()
    wordcount = { word.split(',')[0] : 0 for word in words}

    for line in f2:
        line_split = line.split()
        for word in line_split:
          if word in wordcount: 
            wordcount[word] += 1

print(wordcount)

像往常一样,collections 节省一天的时间:

from collections import Counter

with open('mainWords.txt') as f:
    sentiments = {word: int(value)
                 for word, value in
                 (line.split(",") for line in f)
                 }

with open('sentences.txt') as f:
    for line in f:
        values = Counter(word for word in line.split() if word in sentiments)
        print(values)
        print(sum(values[word]*sentiments[word] for word in values))  # total
        print(len(values))  # keywords

你已经在词典sentiments中找到了情感极性供以后使用。