|
| 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__ importprint_function, division |
| 13 | + |
| 14 | +frompronounceimportread_dictionary |
| 15 | + |
| 16 | + |
| 17 | +defmake_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 | +forlineinfin: |
| 23 | +word=line.strip().lower() |
| 24 | +d[word] =word |
| 25 | + |
| 26 | +returnd |
| 27 | + |
| 28 | + |
| 29 | +defhomophones(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 | +ifanotinphoneticorbnotinphonetic: |
| 38 | +returnFalse |
| 39 | + |
| 40 | +returnphonetic[a] ==phonetic[b] |
| 41 | + |
| 42 | + |
| 43 | +defcheck_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 | +ifword1notinword_dict: |
| 55 | +returnFalse |
| 56 | +ifnothomophones(word, word1, phonetic): |
| 57 | +returnFalse |
| 58 | + |
| 59 | +word2=word[0] +word[2:] |
| 60 | +ifword2notinword_dict: |
| 61 | +returnFalse |
| 62 | +ifnothomophones(word, word2, phonetic): |
| 63 | +returnFalse |
| 64 | + |
| 65 | +returnTrue |
| 66 | + |
| 67 | + |
| 68 | +if__name__=='__main__': |
| 69 | +phonetic=read_dictionary() |
| 70 | +word_dict=make_word_dict() |
| 71 | + |
| 72 | +forwordinword_dict: |
| 73 | +ifcheck_word(word, word_dict, phonetic): |
| 74 | +print(word, word[1:], word[0] +word[2:]) |
0 commit comments