【问题标题】:trouble with analyzing words in one file and checking if they are in each line of another file &… in python无法分析一个文件中的单词并检查它们是否在另一个文件的每一行中&...在python中
【发布时间】: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


    【解决方案1】:

    像往常一样,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 中有情感极性供以后使用。

    【讨论】:

    • 就在我尝试修改代码之前,这种方法会单独计算每行中的关键字数量吗? (如果一个like有4个关键字,那么总数是4个)
    • 对于每一行,它打印一个相关单词的字典和它的频率。所以对于“我只是爱爱爱这个新电影,它是最好的”,它会输出{'love': 3, 'best': 1}。我刚刚明白您所说的“总数”和“关键字”是什么意思,请稍等..
    • @HelloWorld4382 我在print的最后两次调用中添加了如何获取关键字的总数和数量。
    • 很抱歉给您带来了困惑!是的,我正在尝试查找每行中的关键字总数,您看到我如何将关键字与值放在一起了吗?它应该为每一行添加它们.. 例如:“我只是爱爱爱这部新电影,它是最好的”该值将是 = 40,但我会尝试找出那部分
    • 哦,好的!生病检查一下!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 2020-03-10
    • 2020-03-22
    相关资源
    最近更新 更多