📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This module contains a code example related to12Think Python, 2nd Edition3by Allen Downey4http://thinkpython2.com56Copyright 2015 Allen Downey78License: http://creativecommons.org/licenses/by/4.0/9"""1011from __future__ import print_function, division1213from pronounce import read_dictionary141516def make_word_dict():17"""Read. the words in words.txt and return a dictionary18that contains the words as keys."""19d = dict()20fin = open('words.txt')21for line in fin:22word = line.strip().lower()23d[word] = word2425return d262728def homophones(a, b, phonetic):29"""Checks if words two can be pronounced the same way.3031If either word is not in the pronouncing dictionary, return False3233a, b: strings34phonetic: map from words to pronunciation codes35"""36if a not in phonetic or b not in phonetic:37return False3839return phonetic[a] == phonetic[b]404142def check_word(word, word_dict, phonetic):43"""Checks to see if the word has the following property:44removing the first letter yields a word with the same45pronunciation, and removing the second letter yields a word46with the same pronunciation.4748word: string49word_dict: dictionary with words as keys50phonetic: map from words to pronunciation codes51"""52word1 = word[1:]53if word1 not in word_dict:54return False55if not homophones(word, word1, phonetic):56return False5758word2 = word[0] + word[2:]59if word2 not in word_dict:60return False61if not homophones(word, word2, phonetic):62return False6364return True656667if __name__ == '__main__':68phonetic = read_dictionary()69word_dict = make_word_dict()7071for word in word_dict:72if check_word(word, word_dict, phonetic):73print(word, word[1:], word[0] + word[2:])747576