|
| 1 | +"""This module contains a code example related to |
| 2 | +
|
| 3 | +Think Python, 2nd Edition |
| 4 | +by Allen Downey |
| 5 | +http://thinkpython2.com |
| 6 | +
|
| 7 | +Copyright 2015 Allen Downey |
| 8 | +
|
| 9 | +License: http://creativecommons.org/licenses/by/4.0/ |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import print_function, division |
| 13 | + |
| 14 | +from pronounce import read_dictionary |
| 15 | + |
| 16 | + |
| 17 | +def make_word_dict(): |
| 18 | + """Read. the words in words.txt and return a dictionary |
| 19 | + that contains the words as keys.""" |
| 20 | + d = dict() |
| 21 | + fin = open('words.txt') |
| 22 | + for line in fin: |
| 23 | + word = line.strip().lower() |
| 24 | + d[word] = word |
| 25 | + |
| 26 | + return d |
| 27 | + |
| 28 | + |
| 29 | +def homophones(a, b, phonetic): |
| 30 | + """Checks if words two can be pronounced the same way. |
| 31 | +
|
| 32 | + If either word is not in the pronouncing dictionary, return False |
| 33 | +
|
| 34 | + a, b: strings |
| 35 | + phonetic: map from words to pronunciation codes |
| 36 | + """ |
| 37 | + if a not in phonetic or b not in phonetic: |
| 38 | + return False |
| 39 | + |
| 40 | + return phonetic[a] == phonetic[b] |
| 41 | + |
| 42 | + |
| 43 | +def check_word(word, word_dict, phonetic): |
| 44 | + """Checks to see if the word has the following property: |
| 45 | + removing the first letter yields a word with the same |
| 46 | + pronunciation, and removing the second letter yields a word |
| 47 | + with the same pronunciation. |
| 48 | +
|
| 49 | + word: string |
| 50 | + word_dict: dictionary with words as keys |
| 51 | + phonetic: map from words to pronunciation codes |
| 52 | + """ |
| 53 | + word1 = word[1:] |
| 54 | + if word1 not in word_dict: |
| 55 | + return False |
| 56 | + if not homophones(word, word1, phonetic): |
| 57 | + return False |
| 58 | + |
| 59 | + word2 = word[0] + word[2:] |
| 60 | + if word2 not in word_dict: |
| 61 | + return False |
| 62 | + if not homophones(word, word2, phonetic): |
| 63 | + return False |
| 64 | + |
| 65 | + return True |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == '__main__': |
| 69 | + phonetic = read_dictionary() |
| 70 | + word_dict = make_word_dict() |
| 71 | + |
| 72 | + for word in word_dict: |
| 73 | + if check_word(word, word_dict, phonetic): |
| 74 | + print(word, word[1:], word[0] + word[2:]) |
0 commit comments