Hacking Secret Ciphers with Python

(Ann) #1
Chapter 18 – Hacking the Simple Substitution Cipher 261

There must be a value for the pattern key first before we can append word to
allPatterns[pattern], otherwise this would cause an error. So, first line 38 will check if
the pattern is not already in allPatterns. If pattern is not a key in allPatterns yet,
line 39 creates a list with word in it to store in allPatterns[pattern].


If the pattern already is in allPatterns, we do not have to create the list. Line 41 will just
append the word to the list value that is already there.


By the time the for loop that started on line 3 4 finishes, the allPatterns dictionary will
contain the word pattern of each English word that was in wordList as its keys. Each of these
keys has a value that is a list of the words that produce the word pattern. With our data organized
this way, given a word pattern we can easily look up all the English words that produce that
particular pattern.


makeWordPatterns.py
43. # This is code that writes code. The wordPatterns.py file contains
44. # one very, very large assignment statement.
45. fo = open('wordPatterns.py', 'w')
46. fo.write('allPatterns = ')
47. fo.write(pprint.pformat(allPatterns))
48. fo.close()


Now that we have this very large dictionary in allPatterns, we want to save it to a file on the
hard drive. The last part of the main() function will create a file called wordPatterns.py which
will just have one huge assignment statement in it.


Line 45 creates a new file by passing the 'wordPatterns.py' string for the filename and
'w' to indicate that this file will be opened in “write” mode. If there is already a file with the
name 'wordPatterns.py', opening it in write mode will cause the file to be deleted to make
way for the new file we are creating.


Line 4 6 starts the file off with 'allPatterns = ', which is the first part of the assignment
statement. Line 47 finishes it by writing a prettified version of allPatterns to the file. Line
48 closes the file since we are done writing to it.


makeWordPatterns.py
51. if name == 'main':
52. main()

Free download pdf