Count letters in a text file

后端 未结 8 1091
無奈伤痛
無奈伤痛 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:13

    Just for the sake of completeness, if you want to do it without using Counter, here's another very short way, using list comprehension and the dict builtin:

    from string import ascii_lowercase as letters
    with open("text.txt") as f:
        text = f.read().lower()
        print dict((l, text.count(l)) for l in letters)
    

    f.read() will read the content of the entire file into the text variable (might be a bad idea, if the file is really large); then we use a list comprehension to create a list of tuples (letter, count in text) and convert this list of tuples to a dictionary. With Python 2.7+ you can also use {l: text.count(l) for l in letters}, which is even shorter and a bit more readable.

    Note, however, that this will search the text multiple times, once for each letter, whereas Counter scans it only once and updates the counts for all the letters in one go.

提交回复
热议问题