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

Organising iOS OCUnit test files in XCode

ios xcode unit-testing xcode4 ocunit

I am adding unit tests to an existing iOS project using OCUnit with Xcode 4.2. I have successfully added a new build target (following instructions here:

Could someone please help me with some Operating System concepts I cannot grasp - re Interrupts

operating-system interrupt interrupt-handling

Sorry, I wasn't sure if this was a suitable place to ask this, but I hope it is acceptable, apologies if it isn't ! :)

Programmer: Flex 4.5 Pre seleting a Radio Button

xml flash flex actionscript

I'm using an XML File and so far things are OK. But now I'm trying to pre-select a Radio button and I can find no where to give an example just ways to detect click event and thing like that. The

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.