Last active
December 20, 2015 14:09
-
-
Save MattDietz/6144016 to your computer and use it in GitHub Desktop.
Counting word usage. Could be more efficient ways.
This file contains 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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nothing like the internet to make you scramble to fix something stupid in your code.