Fixed CPS (#08) to actually not return anything at the end of functions.

This commit is contained in:
Crista Lopes
2013-11-25 11:27:34 -08:00
parent 1ecf5392bd
commit 190f8301d8

View File

@@ -4,39 +4,39 @@ import sys, re, operator, string
# #
# The functions # The functions
# #
def read_file(path_to_file, func): def read_file(path_to_file, word_freqs, func):
with open(path_to_file) as f: with open(path_to_file) as f:
data = f.read() data = f.read()
return func(data, normalize) func(data, word_freqs, normalize)
def filter_chars(str_data, func): def filter_chars(str_data, word_freqs, func):
pattern = re.compile('[\W_]+') pattern = re.compile('[\W_]+')
return func(pattern.sub(' ', str_data), scan) func(pattern.sub(' ', str_data), word_freqs, scan)
def normalize(str_data, func): def normalize(str_data, word_freqs, func):
return func(str_data.lower(), remove_stop_words) func(str_data.lower(), word_freqs, remove_stop_words)
def scan(str_data, func): def scan(str_data, word_freqs, func):
return func(str_data.split(), frequencies) func(str_data.split(), word_freqs, frequencies)
def remove_stop_words(word_list, func): def remove_stop_words(word_list, word_freqs, func):
with open('../stop_words.txt') as f: with open('../stop_words.txt') as f:
stop_words = f.read().split(',') stop_words = f.read().split(',')
# add single-letter words # add single-letter words
stop_words.extend(list(string.ascii_lowercase)) stop_words.extend(list(string.ascii_lowercase))
return func([w for w in word_list if not w in stop_words], sort) func([w for w in word_list if not w in stop_words], word_freqs, sort)
def frequencies(word_list, func): def frequencies(word_list, word_freqs, func):
word_freqs = {} wf = {}
for w in word_list: for w in word_list:
if w in word_freqs: if w in wf:
word_freqs[w] += 1 wf[w] += 1
else: else:
word_freqs[w] = 1 wf[w] = 1
return func(word_freqs, no_op) func(wf, word_freqs, no_op)
def sort(word_freq, func): def sort(wf, word_freqs, func):
return func(sorted(word_freq.iteritems(), key=operator.itemgetter(1), reverse=True), None) word_freqs.extend(func(sorted(wf.iteritems(), key=operator.itemgetter(1), reverse=True), None))
def no_op(a, func): def no_op(a, func):
return a return a
@@ -44,7 +44,8 @@ def no_op(a, func):
# #
# The main function # The main function
# #
word_freqs = read_file(sys.argv[1], filter_chars) word_freqs = []
read_file(sys.argv[1], word_freqs, filter_chars)
for (w, c) in word_freqs[0:25]: for (w, c) in word_freqs[0:25]:
print w, ' - ', c print w, ' - ', c