【问题标题】:compare words from a list with a text file using counter.collection使用 counter.collection 将列表中的单词与文本文件进行比较
【发布时间】:2021-02-07 07:45:06
【问题描述】:

我正在制作一个小脚本,试图比较文本文件中的单词,现在,我已经能够比较提取所有单词并计算它们的频率,现在,我怎么能让算法只从由我确定的列表中的 .txt... 到目前为止我有这个

from collections import Counter
def word_count(filename):
    with open('hola.txt','r') as f:
        return Counter(f.read().split())

counter = word_count('hola.txt')
for i in counter:
    print (i, ":", counter [i])

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以创建您想要考虑的单词的set,并使用生成器理解为Counter 提供一个仅包含set 中单词的生成器:

    from collections import Counter
    
    words_to_keep = {'only', 'keep', 'these', 'words'}
    
    def word_count(filename):
        with open(filename, 'r') as f: # use `filename`
            return Counter(w for w in f.read().split() if w in words_to_keep)
    
    counter = word_count('hola.txt')
    
    for w, c in counter.items():
        print (w, ":", c)
    

    【讨论】:

      猜你喜欢
      • 2018-08-21
      • 1970-01-01
      • 2012-06-07
      • 2019-04-27
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2012-11-07
      • 2023-03-30
      相关资源
      最近更新 更多