CHARS_TO_REMOVE = '.,"\';:!()?[]' def normalize_word(word): '''Return a word lowercase and stripped of punctuation. NOTE: you don't need to use this function or anything like it for Lab 9. Use the "re.findall" code specified in the lab question instead.''' for char in CHARS_TO_REMOVE: word = word.replace(char, '') return word.lower() def count_words(filename): '''returns a dictionary mapping words to the number of times the word appears in filename''' word_counts = {} # maps words (strings) to occurrences (ints) file = open(filename, errors='ignore') for line in file: line = line.strip() # throw away newline words = line.split() # get all the words in the line for word in words: word = normalize_word(word) # add the word to the map or increase its count word_counts[word] = word_counts.get(word, 0) + 1 file.close() return word_counts def top_words(filename, num_words): '''Return a list of the num_words most frequently occurring words in filename. Each element of the list should be a tuple consisting of (word, frequency).''' word_map = count_words(filename) # construct the word map sorted_keys = sorted(word_map, key=word_map.get) # sorted_keys.reverse() top_list = [] for i in range(num_words): word = sorted_keys[i] word_tuple = (word, word_map[word]) top_list.append(word_tuple) return top_list def unique_words(filename, all_filenames): '''Return a set of words that appear in the string filename but no other files in the list all_filenames''' file_unique_words = set(count_words(filename).keys()) for other_filename in all_filenames: if other_filename != filename: # don't compare a file with itself other_unique_words = set(count_words(other_filename).keys()) file_unique_words -= other_unique_words return file_unique_words def print_reciprocal(number): '''Prints the reciprocal of number''' recip = 1.0 / number print('Reciprocal of {0} is {1}'.format(number, recip)) def print_reciprocal2(number): '''Prints the reciprocal of number''' try: # code that might throw an exception recip = 1.0 / number except: # run this block if there IS an exception print('{0} does not have a reciprocal'.format(number)) else: # run this block if there is NO exception print('Reciprocal of {0} is {1}'.format(number, recip)) def print_reciprocal3(number): '''Prints the reciprocal of number''' try: # code that might throw an exception recip = 1.0 / number except ZeroDivisionError: # run this block if a ZeroDivisionError occurs print('Can\'t divide by zero') except TypeError: # run this block if a TypeError occurs print('{0} is not a number'.format(number)) else: # run this block if there is NO exception print('Reciprocal of {0} is {1}'.format(number, recip))