【问题标题】:Read words from .txt, and count for each words从 .txt 中读取单词,并计算每个单词
【发布时间】:2011-03-28 07:05:04
【问题描述】:

我想知道,如何读取像 fscanf 这样的字符串。我需要在所有 .txt 中逐字阅读。 我需要对每个单词进行计数。

collectwords = collections.defaultdict(int)

with open('DatoSO.txt', 'r') as filetxt:

for line in filetxt:
    v=""
    for char in line:
        if str(char) != " ":
          v=v+str(char)

        elif str(char) == " ":
          collectwords[v] += 1
          v=""

这样一来,我就看不懂最后一个字了。

【问题讨论】:

    标签: python file


    【解决方案1】:

    如果您使用 Python >=2.7,您也可以考虑使用 collections.counter

    http://docs.python.org/library/collections.html#collections.Counter

    它添加了许多方法,例如“most_common”,这可能在此类应用程序中很有用。

    来自 Doug Hellmann 的 PyMOTW:

    import collections
    
    c = collections.Counter()
    with open('/usr/share/dict/words', 'rt') as f:
        for line in f:
            c.update(line.rstrip().lower())
    
    print 'Most common:'
    for letter, count in c.most_common(3):
        print '%s: %7d' % (letter, count)
    

    http://www.doughellmann.com/PyMOTW/collections/counter.html -- 虽然这会计算字母而不是字数。在c.update 行中,您可能希望将line.rstrip().lower 替换为line.split(),并可能需要一些代码来消除标点符号。

    编辑:在这里删除标点符号可能是最快的解决方案:

    import collections
    import string
    
    c = collections.Counter()
    with open('DataSO.txt', 'rt') as f:
        for line in f:
            c.update(line.translate(string.maketrans("",""), string.punctuation).split())
    

    (借自以下问题Best way to strip punctuation from a string in Python

    【讨论】:

      【解决方案2】:

      嗯,像这样?

      with open('DatoSO.txt', 'r') as filetxt:
          for line in filetxt:
              for word in line.split():
                  collectwords[word] += 1
      

      【讨论】:

      • 很好。但是当我打印 :'shoes': 1, 'shoes\n': 5," shoes with \n. without \n.
      • 您可能想在其中添加一个word.strip() (collectwords[word.strip()] += 1) 以删除它周围的任何额外空白。
      • split(' ') 更改为split() 会更好。
      【解决方案3】:

      Python 让这一切变得简单:

      collectwords = []
      filetxt = open('DatoSO.txt', 'r')
      
      for line in filetxt:
        collectwords.extend(line.split())
      

      【讨论】:

      • 我想他想统计出现的次数。
      最近更新 更多