Count letters in a text file

后端 未结 8 1117
無奈伤痛
無奈伤痛 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条回答
  •  旧时难觅i
    2020-12-06 22:05

    You have to use collections.Counter

    from collections import Counter
    text = 'aaaaabbbbbccccc'
    c = Counter(text)
    print c
    

    It prints:

    Counter({'a': 5, 'c': 5, 'b': 5})
    

    Your text variable should be:

    import string
    text = open('text.txt').read()
    # Filter all characters that are not letters.
    text = filter(lambda x: x in string.letters, text.lower())
    

    For getting the output you need:

    for letter, repetitions in c.iteritems():
        print letter, repetitions
    

    In my example it prints:

    a 5
    c 5
    b 5
    

    For more information Counters doc

提交回复
热议问题