#!/usr/local/bin/python # Python solution to 'Simple Code' problem: http://www.cs.duke.edu/csed/code/ # Nadeem Abdul Hamid, Berry College, nadeem@acm.org # March 20, 2007 import sys # for accessing command-line arguments # define a comparison function for (word, freq) pairs... # compares in descending order of frequency, then lexicographical word order def mycmp(x, y): if y[1]==x[1]: return cmp(x[0], y[0]) else: return -cmp(x[1],y[1]) # open file, read in all words, and initialize a dictionary filename = sys.argv[1] f = open(filename) txt = f.read() table = {} # for each word in the file, increment the count in the dictionary # (or set it to 1 if the word has not been encountered before) for word in txt.split(): wl = word.lower() if wl in table: table[wl] = table[wl] + 1 else: table[wl] = 1 # build and sort a list of (word, freq) pairs list = table.items() list.sort(mycmp) # print them out for (word,freq) in list: print str(freq) + '\t' + word