Hacking Secret Ciphers with Python

(Ann) #1
Chapter 12 – Detecting English Programmatically 169

Practice Exercises, Chapter 12, Section A


Practice exercises can be found at http://invpy.com/hackingpractice 12 A.


The Detect English Module


The detectEnglish.py program that we write in this chapter isn’t a program that runs by itself.
Instead, it will be imported by our encryption programs so that they can call the
detectEnglish.isEnglish() function. This is why we don’t give detectEnglish.py a
main() function. The other functions in the program are all provided for isEnglish() to
call.


Source Code for the Detect English Module


Open a new file editor window by clicking on File ► New Window. Type in the following code
into the file editor, and then save it as detectEnglish.py. Press F5 to run the program.


Source code for detectEnglish.py




  1. Detect English module




  2. http://inventwithpython.com/hacking (BSD Licensed)






  3. To use, type this code:




  4. import detectEnglish




  5. detectEnglish.isEnglish(someString) # returns True or False




  6. (There must be a "dictionary.txt" file in this directory with all English




  7. words in it, one word per line. You can download this from




  8. http://invpy.com/dictionary.txt))



  9. UPPERLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

  10. LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n'



  11. def loadDictionary():

  12. dictionaryFile = open('dictionary.txt')

  13. englishWords = {}

  14. for word in dictionaryFile.read().split('\n'):

  15. englishWords[word] = None

  16. dictionaryFile.close()

  17. return englishWords



  18. ENGLISH_WORDS = loadDictionary()





  19. def getEnglishCount(message):

  20. message = message.upper()

  21. message = removeNonLetters(message)

  22. possibleWords = message.split()

Free download pdf