In python, how can I iterate through a text file and count the number of occurrences of each letter? I realise I could just use a ‘for x in file’ statement to go through it and then set up 26 or so if elif statements, but surely there is a better way to do it?
Thanks.
Use
collections.Counter():If the file is not so large, you can read all of it into memory as a string and convert it into a
Counterobject in one line of code:Example:
or use the
count()method of strings: