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