# Program to count words in a file # sort by frequency, then alphabetically # Matt Bishop, February 21, 2012 # for ECS 10 Winter 2012 # # get the input file name # def getfname(): try: fname = input("Enter the file name: ") except EOFError: return None except: print("Error reading file name") return None return fname # # open the file; be graceful on failure # def openfile(fname): try: inpf = open(fname) except: print("Could not open file!") inpf = None return inpf # # return a tuple for sorting # first key is frequency, second is word # def alphafreq(x): return x[1], x[0] # # this does the actual work # def main(): # # get file name # fname = getfname() if fname == None: return # # open the file # fc = openfile(fname) if fc == None: return # # create empty dictionary # d = dict() # read the fileline by line, and get # the words # words are separated by whitespace for line in fc.readlines(): # split into words words=line.split(' ') for tmpword in words: # now eliminate all non-alphanumerics word = "" for i in tmpword: if i.isalnum(): word = word + i # if we don't have anything, skip it # otherwise, enter it into the dictionary if word != "": d[word] = d.get(word, 0) + 1 # # sort on the keys # worditems = list(d.items()) # # print them out # for k in sorted(worditems, key=lambda x: alphafreq(x)): print("%-30s%5d" % k) # # go! # main()