Hacking Secret Ciphers with Python

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

wordsMatch. (Remember, the >= comparison operator evaluates expressions to a Boolean
value.) Otherwise, False is stored in wordsMatch.


detectEnglish.py
52. numLetters = len(removeNonLetters(message))
53. messageLettersPercentage = float(numLetters) / len(message) * 100
54. lettersMatch = messageLettersPercentage >= letterPercentage


Lines 52 to 54 calculate the percentage of letter characters in the message string. To determine
the percentage of letter (and space) characters in message, our code must divide the number of
letter characters by the total number of characters in message. Line 52 calls
removeNonLetters(message). This call will return a string that has the number and
punctuation characters removed from the string. Passing this string to len() will return the
number of letter and space characters that were in message. This integer is stored in the
numLetters variable.


Line 53 determines the percentage of letters getting a float version of the integer in
numLetters and dividing this by len(message). The return value of len(message) will
be the total number of characters in message. (The call to float() was made so that if the
programmer who imports our detectEnglish module is running Python 2, the division done
on line 53 will always be regular division instead of integer division.)


Line 54 checks if the percentage in messageLettersPercentage is greater than or equal to
the letterPercentage parameter. This expression evaluates to a Boolean value that is stored
in lettersMatch.


detectEnglish.py
55. return wordsMatch and lettersMatch


We want isEnglish() to return True only if both the wordsMatch and lettersMatch
variables contain True, so we put them in an expression with the and operator. If both the
wordsMatch and lettersMatch variables are True, then isEnglish() will declare that
the message argument is English and return True. Otherwise, isEnglish() will return
False.


Practice Exercises, Chapter 12, Set E


Practice exercises can be found at http://invpy.com/hackingpractice12E.

Free download pdf