【问题标题】:Count every word in a text file python计算文本文件python中的每个单词
【发布时间】:2013-08-29 08:09:31
【问题描述】:

我想要的是能够输入一个多行文本文件,它就像一个段落一样长,然后返回如下内容:

{'Total words': 'NUMBER', 'Words ending with LY': 'NUMBER'}

我以前从未使用过 Counter,但我相信我会这样做。所以我希望它计算每个单词,如果单词以 LY 结尾,则将其添加到第二个计数中。考虑到我从未使用过 Counter 我不知道该去哪里......

with open('SOMETHING.txt') as f:
  # something to do with counter here?

编辑:我必须在不使用计数器的情况下这样做!如果没有计数器库,我如何获得相同的结果?

【问题讨论】:

    标签: python python-3.x counter


    【解决方案1】:

    这应该适合你...

    def parse_file():
      with open('SOMETHING.txt', 'r') as f:
        c1 = 0
        c2 = 0
        for i in f:
          w = i.split()
          c1 += len(w)
          for j in w:
            if j.endswith('LY'):
              c2 += 1
        return {'Total words': c1, 'Words ending with LY': c2}
    

    不过,我建议您查看a few python basics

    【讨论】:

    • 试试吧。随意:)
    【解决方案2】:

    这很难尝试吗?

    from collections import defaultdict
    result = defaultdict(int)
    result_second = defaultdict(int)
    for word in open('text.txt').read().split():
        result[word] += 1
        if word.endswith('LY'): 
            result_second[word] +=1
    print result,result_second
    

    输出:

    defaultdict(<type 'int'>, {'and': 1, 'Considering': 1, 'have': 2, "don't": 1, 'is': 1, 'it': 2, 'second': 1, 'want': 1, 'in': 1, 'before': 1, 'would': 1, 'to': 3, 'count.': 1, 'go...': 1, 'how': 1, 'add': 1, 'if': 1, 'LY': 1, 'it.': 1, 'do': 1, 'ends': 1, 'used': 2, 'that': 1, 'I': 1, 'Counter': 2, 'but': 1, 'So': 1, 'know': 1, 'never': 2, 'believe': 1, 'count': 1, 'word': 2, 'i': 5, 'every': 1, 'the': 2, 'where': 1})
    

    【讨论】:

      【解决方案3】:

      使用 collections.Counter()

      import collections
      
      with open('your_file.txt') as fp:
          text = fp.read()
          counter = collections.Counter(['ends_in_ly' if token.endswith('LY') else 'doesnt_end_in_ly' for token in text.split()])
      

      无计数器

      with open('file.txt') as fp:
          tokens = fp.read().split()
          c = sum([1 if token.endswith('LY') else 0 for token in tokens])
          return {'ending_in_ly': c, 'not_ending_in_ly': len(tokens) - c}
      

      【讨论】:

      • 我添加了一个没有计数器的解决方案。
      • 小心,read() 会将整个文件加载到内存中。如果文件很大,可能会耗尽系统的 RAM 内存。