freq.py

import word

def word_freq(filename):
	hist = {}
	with open(filename) as f:
		for w in word.next_word(f):
			hist[w] = hist.get(w, 0) + 1
	return hist

def print_freq(hist, top=10):
	# Use list comprehension to construct sortable list
	by_count = [(count, word) for (word, count) in hist.items()]
	# "sorted" defaults to ascending order, use "reverse" for descending
	for count, word in sorted(by_count, reverse=True)[:top]:
		print "\t%s: %d" % (word, count)

if __name__ == "__main__":
	filename = "../bee.txt"
	print "%s:" % filename
	print_freq(word_freq(filename), 5)