Hacking Secret Ciphers with Python

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

detectEnglish.py


  1. return ''.join(lettersOnly)


After line 41’s for loop is done, only the letter and space characters are in the lettersOnly
list. To make a single string value from this list of strings, we call the join() string method on
a blank string. This will join the strings in lettersOnly together with a blank string (that is,
nothing) between them. This string value is then returned as removeNonLetters()’s return
value.


Default Arguments


detectEnglish.py


  1. def isEnglish(message, wordPercentage=20, letterPercentage= 85 ):


  2. By default, 20% of the words must exist in the dictionary file, and




  3. 85% of all the characters in the message must be letters or spaces




  4. (not punctuation or numbers).




The isEnglish() function will accept a string argument and return a Boolean value that
indicates whether or not it is English text. But when you look at line 47, you can see it has three
parameters. The second and third parameters (wordPercentage and letterPercentage)


have equal signs and values next to them. These are called default arguments. Parameters that
have default arguments are optional. If the function call does not pass an argument for these
parameters, the default argument is used by default.


If isEnglish() is called with only one argument, the default arguments are used for the
wordPercentage (the integer 20 ) and letterPercentage (the integer 85 ) parameters.
Table 12-1 shows function calls to isEnglish(), and what they are equivalent to:


Table 12 - 1. Function calls with and without default arguments.
Function Call Equivalent To
isEnglish('Hello') isEnglish('Hello', 20, 85)

isEnglish('Hello', 50) isEnglish('Hello', 50, 85)

isEnglish('Hello', 50, 60) isEnglish('Hello', 50, 60)

isEnglish('Hello',
letterPercentage=60)

isEnglish('Hello', 20, 60)
Free download pdf