# Program to count words in a file # prints them out unsorted # 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 # # 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 # # print them out # for k in d.keys(): print("%-30s%5d" % (k, d[k])) # # go! # main()