-
Notifications
You must be signed in to change notification settings - Fork 148
/
makeWordPatterns.py
52 lines (39 loc) · 1.38 KB
/
makeWordPatterns.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
# Makes the wordPatterns.py File
# http://inventwithpython.com/hacking (BSD Licensed)
# Creates wordPatterns.py based on the words in our dictionary
# text file, dictionary.txt. (Download this file from
# http://invpy.com/dictionary.txt)
import pprint
def getWordPattern(word):
# Returns a string of the pattern form of the given word.
# e.g. '0.1.2.3.4.1.2.3.5.6' for 'DUSTBUSTER'
word = word.upper()
nextNum = 0
letterNums = {}
wordPattern = []
for letter in word:
if letter not in letterNums:
letterNums[letter] = str(nextNum)
nextNum += 1
wordPattern.append(letterNums[letter])
return '.'.join(wordPattern)
def main():
allPatterns = {}
fo = open('dictionary.txt')
wordList = fo.read().split('\n')
fo.close()
for word in wordList:
# Get the pattern for each string in wordList.
pattern = getWordPattern(word)
if pattern not in allPatterns:
allPatterns[pattern] = [word]
else:
allPatterns[pattern].append(word)
# This is code that writes code. The wordPatterns.py file contains
# one very, very large assignment statement.
fo = open('wordPatterns.py', 'w')
fo.write('allPatterns = ')
fo.write(pprint.pformat(allPatterns))
fo.close()
if __name__ == '__main__':
main()