# Program to count words in a file # Matt Bishop, ECS 10, Fall 2012 # # get the input file name # def getfname(): try: fname = input("Enter the file name: ") except EOFError: # exit gracefully return None except: # report problem and exit gracefully 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 # # 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: x[1]): print("%-30s%5d" % k) # # go! # main()