Skip to content

Instantly share code, notes, and snippets.

@peterarnott
Last active August 29, 2015 13:59
Show Gist options
  • Save peterarnott/10574510 to your computer and use it in GitHub Desktop.
Save peterarnott/10574510 to your computer and use it in GitHub Desktop.
Count the words in a book!
import string
from collections import defaultdict
frequencies = defaultdict(int)
for line in open("book.txt"):
for word in line.lower().translate(None, string.punctuation).split():
frequencies[word] += 1
sortedlist = sorted(frequencies.items(), key=lambda x: (-x[1],x[0]), reverse=False)
with open('results.txt', 'w') as f:
for item in sortedlist:
formatted = "\"%s\": %d\n" % (item[0], int(item[1]))
f.write(formatted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment