1. 程式人生 > 實用技巧 >計算機如何區分亂碼和英文?

計算機如何區分亂碼和英文?

一個大的字串加密之後就是亂碼了,一般來說看不出其字面意思,我們需要正確的解密

而解密後,計算機要怎惡麼知道解密是否成功呢?

isEnglish()函式會把解密後的字串分割成單詞s,檢查每個單詞是否在包含成千上萬個英文單詞的檔案裡,

儘管這個檔案不能說包含所有單詞。現在,如果一定數量的單詞s是英文單詞,那麼我們可以大概率的說

這些文字是英文,也就是說我們有信心說找到了正確的金鑰,解密成功。


這裡定義了一種計算機如何區分亂碼和英文de方法:

# Detect English module
# http://inventwithpython.com/hacking (BSD Licensed)

#
To use, type this code: # import detectEnglish # detectEnglish.isEnglish(someString) # returns True or False # (There must be a "dictionary.txt" file in this directory with all English # words in it, one word per line. You can download this from # http://invpy.com/dictionary.txt) # 好的習慣 常量大寫命名!! ' \t\n'分別是 空格 (兩個轉義字元)製表符 和 換行字元
UPPERLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n' def loadDictionary(): dictionaryFile = open('dictionary.txt') # englishWords = {}定義了一個空的字典 englishWords = {} # 把所有的單詞設成這個字典的鍵key,其對應的值都為None # dictionaryFile.read().split('\n')這是一個列表,read()讀出了整個文件內容
# 成了一個大的字串,split('\n')方法將其分割組成列表 # (因為這個檔案中每一行只有一個單詞) for word in dictionaryFile.read().split('\n'): # 我們不在乎每個鍵裡面儲存了什麼值,所以用None 屬於NoneType資料型別 # 表示這個值暫且不存在,我也說不好他是什麼以及會是什麼 englishWords[word] = None dictionaryFile.close() return englishWords # 裝載一個字典 在detectEnglish的全域性程式碼塊中,任何import detectEnglish的 # Python程式都可以看見並使用 ENGLISH_WORDS = loadDictionary() # 接受一個字串引數,返回一個浮點值,比例(沒有一個0~1全是),表示已經識別出了多少個英文單詞 def getEnglishCount(message): message = message.upper() message = removeNonLetters(message) possibleWords = message.split() # 考慮到message可能是一個不是英文字母的字串如'1234568' 那麼呼叫removeNonLetters # 返回了空的字串,然後經過split()方法轉化成空的列表 這種情況要return出去 if possibleWords == []: return 0.0 # no words at all, so return 0.0 matches = 0 for word in possibleWords: if word in ENGLISH_WORDS: matches += 1 # 我們在python中使用除法的時候要避免除以0錯誤,這裡這種錯誤不會發生,因為如果possibleWords # 是空列表時在上面已經return出去了,這是一種處理除以0錯誤的辦法 return float(matches) / len(possibleWords) # 移除特殊符號和數字(不在LETTERS_AND_SPACE中的字串) def removeNonLetters(message): lettersOnly = [] for symbol in message: if symbol in LETTERS_AND_SPACE: lettersOnly.append(symbol) return ''.join(lettersOnly) # 判斷是英文字是通過設定字母和單詞所佔的比例,即設定閾值來判斷的 def isEnglish(message, wordPercentage=20, letterPercentage=85): # By default, 20% of the words must exist in the dictionary file, and # 85% of all the characters in the message must be letters or spaces # (not punctuation or numbers). wordsMatch = getEnglishCount(message) * 100 >= wordPercentage numLetters = len(removeNonLetters(message)) messageLettersPercentage = float(numLetters) / len(message) * 100 lettersMatch = messageLettersPercentage >= letterPercentage return wordsMatch and lettersMatch

這個程式碼可能對我們的其他破譯程式有用,所以把它做成單獨的模組,以便其他想要呼叫isEnglish()的程式匯入。

這樣使用

>>> import detectEnglish
>>> detectEnglish.isEnglish('is this sentence English text?')
True
>>>