Last active
August 29, 2015 13:59
-
-
Save peterarnott/10574510 to your computer and use it in GitHub Desktop.
Count the words in a book!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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