How can I count the number of times each word appears in a txt file?

You should go off and do your own homework to help you learn. But regardless, here is a solution.

#!/usr/bin/env python

dict = {}

with open("trash.dat", "rw") as f:
    for line in f:
        if line != "\n":
            if line.lower() in dict:
                dict[line.lower()] = dict[line.lower()] + 1
            else:
                dict[line.lower()] = 1

for x in dict:
    print "%s=" % x, dict[x]

Leave a Comment