# Program to count words in a file # prints them out unsorted # # Matt Bishop, ECS 10, Spring 2014 # # for homework #5, problem 1 (and the others) # import string # # break a line into maximal sequences of letters, numbers, and digits # def listofwords(s): # initialize the list for the words # and the string to collect characters for the current word l = [] t = "" # # walk through the line a character at a time # for i in s: # if the current char isn't in a word, it ends it if i not in string.ascii_letters + string.digits + '_': # if not currently in a word, ignore it if t != "": # in a word; append the word to the list of words # and clear the string to begin collecting chars # for the next word l.append(t) t = "" # current char not in the a word; loop continue # the current char is in a word, so add it to the chars # collected so far t += i # # done! return the list of words # return l # # 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() # # begin with line 1 # lineno = 0 # read the fileline by line, and get # the words # words are separated by whitespace for line in fc.readlines(): # read another line lineno += 1 # split into words words=listofwords(line) for word in words: # if we don't have anything, skip it # otherwise, enter it into the dictionary d[word] = d.get(word, 0) + 1 # # print them out # for k in d: print("%-27s %d" % (k, d[k])) # # go! # main()