Skip to content

Instantly share code, notes, and snippets.

@MattDietz
Last active December 20, 2015 14:09
Show Gist options
  • Save MattDietz/6144016 to your computer and use it in GitHub Desktop.
Save MattDietz/6144016 to your computer and use it in GitHub Desktop.
Counting word usage. Could be more efficient ways.
import re
data = open("a bunch of text", 'r')
words = {}
strip_punc = re.compile("[!.,]")
whitespace_collapse = re.compile("\s+")
for line in data.readlines():
line = strip_punc.sub('', line)
line = whitespace_collapse.sub(' ', line)
line = line.lower()
tokens = line.split(' ')
for token in tokens:
if token not in words:
words[token] = 0
words[token] += 1
sorted_words = sorted(words.iteritems(), key=lambda x: x[1])
print sorted_words
@MattDietz
Copy link
Author

Nothing like the internet to make you scramble to fix something stupid in your code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment