【发布时间】:2016-11-15 12:33:20
【问题描述】:
所以,我试图搜索 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 次,然后爱:43,但我m 为每一行寻找单独的列表.. 所以如果一行包含 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)
【问题讨论】:
标签: python python-3.x sentiment-analysis