Find Word Count in File With Python

by Doug Sparling

Single word per line:

import collections
import operator
import os
import re</code>

infile = open("words1.txt")
words = collections.Counter()

for line in infile:
    words.update([line.rstrip(os.linesep)])

sorted_words = sorted(words.iteritems(), key=operator.itemgetter(1), reverse=True)

for word, count in sorted_words:
    print word, count

First word in space separated line:

import collections
import operator
import re</code>

infile = open("words2.txt")
words = collections.Counter()

for line in infile:
    the_line = re.split('\s+', line)
    the_word = the_line[0]
    words.update([the_word])

sorted_words = sorted(words.iteritems(), key=operator.itemgetter(1), reverse=True)

for word, count in sorted_words:
    print word, count