Count letters in a text file

后端 未结 8 1005
無奈伤痛
無奈伤痛 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 22:04

    Yet another way:

    import sys
    from collections import defaultdict
    
    read_chunk_size = 65536
    
    freq = defaultdict(int)
    for c in sys.stdin.read(read_chunk_size):
        freq[ord(c.lower())] += 1
    
    for symbol, count in sorted(freq.items(), key=lambda kv: kv[1], reverse=True):
        print(chr(symbol), count)
    
    

    It outputs the symbols most frequent to the least.

    The character counting loop is O(1) complexity and can handle arbitrarily large files because it reads the file in read_chunk_size chunks.

提交回复
热议问题