Hacking Secret Ciphers with Python

(Ann) #1

254 http://inventwithpython.com/hacking


Email questions to the author: [email protected]







  1. def getWordPattern(word):


  2. Returns a string of the pattern form of the given word.




  3. e.g. '0.1.2.3.4.1.2.3.5.6' for 'DUSTBUSTER'



  4. word = word.upper()

  5. nextNum = 0

  6. letterNums = {}

  7. wordPattern = []



  8. for letter in word:

  9. if letter not in letterNums:

  10. letterNums[letter] = str(nextNum)

  11. nextNum += 1

  12. wordPattern.append(letterNums[letter])

  13. return '.'.join(wordPattern)





  14. def main():

  15. allPatterns = {}



  16. fo = open('dictionary.txt')

  17. wordList = fo.read().split('\n')

  18. fo.close()



  19. for word in wordList:


  20. Get the pattern for each string in wordList.



  21. pattern = getWordPattern(word)



  22. if pattern not in allPatterns:

  23. allPatterns[pattern] = [word]

  24. else:

  25. allPatterns[pattern].append(word)




  26. This is code that writes code. The wordPatterns.py file contains




  27. one very, very large assignment statement.



  28. fo = open('wordPatterns.py', 'w')

  29. fo.write('allPatterns = ')

  30. fo.write(pprint.pformat(allPatterns))

  31. fo.close()





  32. if name == 'main':

  33. main()

Free download pdf