Count letters in a text file

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

    Using re:

    import re
    
    context, m = 'some file to search or text', {}
    letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    for i in range(len(letters)):
      m[letters[i]] = len(re.findall('{0}'.format(letters[i]), context))
      print '{0} -> {1}'.format(letters[i], m[letters[i]])
    

    It is much more elegant and clean with Counter nonetheless.

提交回复
热议问题