def word_freq(f):
hist = {}
for line in f:
for word in line.split():
hist[word] = hist.get(word, 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"
with open(filename) as f:
print("%s:" % filename)
print_freq(word_freq(f), 5)