From a93c51c221dae727563f348f1b7f0dbe9710cf17 Mon Sep 17 00:00:00 2001 From: Crista Lopes Date: Wed, 25 Sep 2013 07:53:55 -0700 Subject: [PATCH] Added style #17 --- 17-introspective/README.md | 15 +++++++++++ 17-introspective/tf-17.py | 54 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 17-introspective/README.md create mode 100644 17-introspective/tf-17.py diff --git a/17-introspective/README.md b/17-introspective/README.md new file mode 100644 index 0000000..e121108 --- /dev/null +++ b/17-introspective/README.md @@ -0,0 +1,15 @@ +Style #17 +============================== + +Constraints: + +- The problem is decomposed using some form of abstraction (procedures, functions, objects, etc.) + +- The abstractions have access to information about themselves, although they cannot modify that information + + +Possible names: + +- Introspective +- Navel-gazing + diff --git a/17-introspective/tf-17.py b/17-introspective/tf-17.py new file mode 100644 index 0000000..3ec896e --- /dev/null +++ b/17-introspective/tf-17.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python + +import sys, re, operator, string, inspect + +# +# The functions +# +def extract_words(path_to_file): + """ + Takes a path to a file and returns the non-stop + words, after properly removing nonalphanumeric chars + and normalizing for lower case + """ + print "My name is " + inspect.stack()[0][3] + " and my arguments are " + str(locals().keys()) + with open(locals()['path_to_file']) as f: + str_data = f.read() + pattern = re.compile('[\W_]+') + word_list = pattern.sub(' ', str_data).lower().split() + with open('../stop_words.txt') as f: + stop_words = f.read().split(',') + stop_words.extend(list(string.ascii_lowercase)) + return [w for w in word_list if not w in stop_words] + +def frequencies(word_list): + """ + Takes a list of words and returns a dictionary associating + words with frequencies of occurrence + """ + print "My name is " + inspect.stack()[0][3] + " and my arguments are " + str(locals().keys()) + word_freqs = {} + for w in locals()['word_list']: + if w in word_freqs: + word_freqs[w] += 1 + else: + word_freqs[w] = 1 + return word_freqs + +def sort(word_freq): + """ + Takes a dictionary of words and their frequencies + and returns a list of pairs where the entries are + sorted by frequency + """ + print "My name is " + inspect.stack()[0][3] + " and my arguments are " + str(locals().keys()) + return sorted(locals()['word_freq'].iteritems(), key=operator.itemgetter(1), reverse=True) + +# +# The main function +# +word_freqs = sort(frequencies(extract_words(sys.argv[1]))) + +for tf in word_freqs[0:25]: + print tf[0], ' - ', tf[1] +