字母频率替换密码



我的代码无法正确执行此替换密码,我的提示如下:假设密码文本和接受的英语频率之间的字母频率对应,解密密码文件;即,如果密码文本中最常见的字母是"p",则假定它是明文中的"e";如果密码文本中第二常见的字母是"o",则假定它是明文中的"t";等

alpha = [[0,'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']]
fre = ["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"]
file = str(input(":"))
text = file.upper()
for c in text:
for e in alpha:
if c == e[0]:
e[0] += 1
for e in alpha:
e[0] = text.count(e[1])
alpha.sort()
alpha.reverse()
print(alpha)
text = text.replace(alpha[0][1],"e")
text = text.replace(alpha[1][1],"t")
text = text.replace(alpha[2][1],"a")
text = text.replace(alpha[3][1],"o")
text = text.replace(alpha[4][1],"i")
text = text.replace(alpha[5][1],"n")
text = text.replace(alpha[6][1],"s")
text = text.replace(alpha[7][1],"h")
text = text.replace(alpha[8][1],"r")
text = text.replace(alpha[9][1],"d")
text = text.replace(alpha[10][1],"l")
text = text.replace(alpha[11][1],"c")
text = text.replace(alpha[12][1],"u")
text = text.replace(alpha[13][1],"m")
text = text.replace(alpha[14][1],"w")
text = text.replace(alpha[15][1],"f")
text = text.replace(alpha[16][1],"g")
text = text.replace(alpha[17][1],"y")
text = text.replace(alpha[18][1],"p")
text = text.replace(alpha[19][1],"b")
text = text.replace(alpha[20][1],"v")
text = text.replace(alpha[21][1],"k")
text = text.replace(alpha[22][1],"j")
text = text.replace(alpha[23][1],"x")
text = text.replace(alpha[24][1],"q")
text = text.replace(alpha[25][1],"z")
print(text)

当您按顺序执行replace时,似乎存在混淆的可能性:假设"p"是密码中最常见的字符,并将其替换为"e"。稍后,您将用其他内容替换"e",这将再次扰乱您的结果。我会试试这样的东西(在你把alpha按你喜欢的方式排序之后(:

''.join(map(dict(zip(fre, map(lambda a: a[1], alpha))).get, text))

它创建了一个从密码文本到英语文本的映射,并将其直接应用于文本。

您还可以动态生成列表alpha

from string import ascii_letters
alpha = []
fre = ["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"]
text = "rsy yrr"    # cipher of "eat tee"
for letter in ascii_letters:
n = text.count(letter)
if n:
alpha.append([n, letter])

然后按降序排序:

alpha.sort(reverse=True)

然后提取字母并制作一本字典,将加密字母映射为解密字母:

letters_by_freq = [pair[1] for pair in alpha]
deciph_dict = dict(zip(letters_by_freq, fre))

最后使用字符串翻译表替换所有字母:

trans_table = str.maketrans(deciph_dict)
print(text.translate(trans_table))

输出:eat tee

最新更新