# Tabulator Example # Source code file: tabulator.py import re # Define empty dictionary. d = { } # Open input file. fin = open('cinderella.txt', 'r') # Define all punctuation to remove. reg_exp = r'''[\.,;:"!?]+''' # Define # Throw away first line. fin.readline( ) for line in fin: # Convert line to lower case. line = line.lower( ) # Remove whitespace from beginning and # end of line. line = line.strip( ) # Remove all punctuation. line = re.sub(reg_exp, '', line) # Extract words from line. # \s means any whitespace character # same as [ \n\r\f\t\v] words = re.split(r'\s+', line) # If word is in dictionary, increment count; # if word is not in dictionary, add to # dictionary, setting count to 1 for word. for word in words: if word in d: d[word] += 1 else: d[word] = 1 # Print dictionary # print(d) # Copy dictionary items into list of lists. items = [ ] for k in d.keys( ): items.append([d[k], k]) # Sort list of lists in reverse order. items.sort(reverse = True) # Print items in list of lists. for item in items: print(f'{item[1]} {item[0]}')