我目前正在編寫一個代碼,我想計算在密文中使用的字母的頻率,然後將其與ETAOINSHRDLCUMWFGYPBVKJXQZ
進行比較。然後,我希望它提供解密時使用的密鑰,但是我無法從當前編碼獲得輸出。我試圖創建一個caeser密碼的頻率分析,但我似乎無法得到一個輸出
englishLetterFreq = {'E', 'T', 'A', 'O', 'I', 'N', 'S', 'H', 'R', 'D', 'L', 'C', 'U', 'M', 'W', 'F', 'G', 'Y', 'P', 'B', 'V', 'K', 'J', 'X', 'Q', 'Z'}
ETAOIN = 'ETAOINSHRDLCUMWFGYPBVKJXQZ'
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def getLetterCount(message):
letterCount = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'J': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'O': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0, 'X': 0, 'Y': 0, 'Z': 0}
for letter in message.upper():
if letter in LETTERS:
letterCount[letter] +=1
print('LETTERS {}'.format(letterCount))
return letterCount
def getItemAtIndexZero(x):
return x[0]
def getFrequencyOrder(message):
letterToFreq = getLetterCount(message)
letterToFreq = {}
for letter in LETTERS:
if letterToFreq[letter] not in freqToletter:
freqToLetter[letterToFreq[letter]] = [letter]
else:
freqToLetter[letterToFreq[letter]].append(letter)
for freq in freqToLetter:
freqToLetter[freq].sort(key=ETAOIN.find, reverse=True)
freqToLetter[freq] = ".join(freqToLetter[freq])"
freqPairs = list(freqToLetter.items())
freqPairs.sort(key=getItemAtIndexZero, reverse=True)
freqOrder = []
for freqPair in freqPairs:
freqOrder.append(freqPair[1])
return".join(freqOrder)"
def englishFreqMatchScore(message):
freqOrder = getFrequencyOrder(message)
matchScore = 0
for commonLetter in ETAOIN[:6]:
if commonLetter in freqOrder[:6]:
matchScore += 1
for uncommonLetter in ETAOIN[-6:]:
if uncommonLetter in freqOrder[-6:]:
matchScore += 1
print("{}",englsishFreqMatchScore)
return matchScore
您的代碼格式出錯了。請參閱[Markdown幫助 - 代碼和預格式化文本](http://stackoverflow.com/editing-help#code)和[編輯]您的文章。 – Kevin
一般說明。這是稍微先進的,但看看https://docs.python.org/2/library/collections.html#collections.Counter這將爲您節省很多時間,並在將來用這種類型的任務 –
爲什麼要在下面一行覆蓋它時調用getLetterCount – Navidad20