260 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
'0.1.1.2') and the keys’ values are a list of strings of English words that match that pattern.
For example, here’s one of the key-value pairs that will end up in allPatterns:
'0.1.0.2.3.1.4': ['DEDUCER', 'DEDUCES', 'GIGABIT', 'RARITAN']
But at the beginning of the main() function on line 28, the allPatterns variable will start
off as a blank dictionary value.
makeWordPatterns.py
30. fo = open('dictionary.txt')
31. wordList = fo.read().split('\n')
32. fo.close()
Lines 30 to 32 read in the contents of the dictionary file into wordList. Chapter 11 covered
these file-related functions in more detail. Line 30 opens the dictionary.txt file in “reading” mode
and returns a file object. Line 31 calls the file object’s read() method which returns a string of
all text from this file. The rest of line 31 splits it up whenever there is a \n newline character, and
returns a list of strings: one string per line in the file. This list value returned from split() is
stored in the wordList variable. At this point we are done reading the file, so line 34 calls the
file object’s close() method.
The wordList variable will contain a list of tens of thousands of strings. Since the
dictionary.txt file has one English word per line of text, each string in the wordList variable
will be one English word.
makeWordPatterns.py
34. for word in wordList:
35. # Get the pattern for each string in wordList.
36. pattern = getWordPattern(word)
The for loop on line 34 will iterate over each string in the wordList list and store it in the
word variable. The word variable is passed to the getWordPattern() function, which
returns a word pattern string for the string in word. The word pattern string is stored in a variable
named pattern.
makeWordPatterns.py
38. if pattern not in allPatterns:
39. allPatterns[pattern] = [word]
40. else:
41. allPatterns[pattern].append(word)