Count letters in a text file

后端 未结 8 1122
無奈伤痛
無奈伤痛 2020-12-06 21:13

I am a beginner python programmer and I am trying to make a program which counts the numbers of letters in a text file. Here is what I\'ve got so far:

import         


        
8条回答
  •  醉话见心
    2020-12-06 21:54

    You could split the problem into two simpler tasks:

    #!/usr/bin/env python
    import fileinput # accept input from stdin and/or files specified at command-line
    from collections import Counter
    from itertools import chain
    from string import ascii_lowercase
    
    # 1. count frequencies of all characters (bytes on Python 2)
    freq = Counter(chain.from_iterable(fileinput.input())) # read one line at a time
    
    # 2. print frequencies of ascii letters
    for c in ascii_lowercase:
         n = freq[c] + freq[c.upper()] # merge lower- and upper-case occurrences
         if n != 0:
            print(c, n)
    

提交回复
热议问题