【问题标题】:Using a Text file to count certain words in PYTHON使用文本文件计算 PYTHON 中的某些单词
【发布时间】:2018-10-20 09:51:10
【问题描述】:

我需要很多帮助。我正在尝试使用文本文件来仅计算文本中的某些单词。我一直在寻找几个小时来尝试寻求帮助,但似乎找不到任何帮助。

需要区分大小写 我需要使用的词是: 很棒,很好,完美,很好,很棒,很喜欢,很喜欢,很开心,很喜欢,很棒

【问题讨论】:

  • 很抱歉,除非您展示您的尝试,否则我们无法帮助您。寻找有关如何从文本文件中读取的教程。如何遍历您读取的数据以及如何将迭代与您的单词列表进行比较(有一种特定的方法可以强制区分大小写,并在匹配时增加您的计数器。祝你好运

标签: python


【解决方案1】:

您可以使用“re.findall”或“re.finditer”等正则表达式来搜索单词,然后遍历整个文件。

    list = []
    with open("file.txt") as f:
        words = f.read()
        list.append(re.findall(r"great", words))

然后你可以通过 len 函数来统计单词。 代码可能需要根据要求进行少量修改。 浏览正则表达式页面以获取更多信息。

你甚至可以使用 str.count()。

【讨论】:

    【解决方案2】:

    collections.Counter 提供了许多单词计数选项

    from collections import Counter
    
    with open('alice.txt') as f:
        content = f.read()
    
    c = Counter(content.split())
    
    print(c['you'])
    
    lst = ['me', 'them', 'us']
    
    for i in lst:
        print(f'{i}: {c[i]}')
    
    for word, count in c.most_common(5):
        print(word + ':', count)
    
    301
    me: 46
    them: 49
    us: 10
    the: 1664
    and: 780
    to: 773
    a: 662
    of: 596
    

    【讨论】:

      猜你喜欢
      • 2014-11-04
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-12
      相关资源
      最近更新 更多