字母频率替换密码

时间:2018-11-23 23:17:03

标签: python

我在让我的代码正确执行此替换密码时遇到麻烦,我的提示如下:假设密码文本与接受的英语频率之间的字母频率对应,解密一个密码文件;即,如果密文中最常见的字母是“ 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)

2 个答案:

答案 0 :(得分:0)

当您依次执行replace时,似乎有混淆的可能性:假设“ p”是密码中最常见的字符,然后将其替换为“ e”。稍后,您将用“ e”替换其他内容,这将再次使您的结果混乱。 我会尝试类似的方法(在您对alpha进行了排序之后):

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

这将创建从密文到英文文本的映射,并将其直接应用于文本。

答案 1 :(得分:0)

您还可以随时添加列表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