Count frequency of letters in a text file

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.

Answers


Use collections.Counter():

from collections import Counter
with open(file) as f:
    c = Counter()
    for x in f:
        c += Counter(x.strip())

As @mgilson pointed out, in case if the file is not so large,you can simply do :

c = Counter(f.read().strip())

example:

>>> c = Counter()
>>> c += Counter('aaabbbcccddd eee fff ggg')
>>> c
Counter({'a': 3, ' ': 3, 'c': 3, 'b': 3, 'e': 3, 'd': 3, 'g': 3, 'f': 3})
>>> c += Counter('aaabbbccc')
Counter({'a': 6, 'c': 6, 'b': 6, ' ': 3, 'e': 3, 'd': 3, 'g': 3, 'f': 3})

or use the count() method of strings:

from string import ascii_lowercase     # ascii_lowercase =='abcdefghijklmnopqrstuvwxyz'
with open(file) as f:
    text = f.read().strip()
    dic = {}
    for x in ascii_lowercase:
        dic[x] = text.count(x)

Need Your Help

Why can't I declare static methods in an interface?

java interface methods static

The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.