字母频率替代ciph

2024-06-11 10:48:02 发布

您现在位置: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)

Tags: 代码textin文本alpha语言密码for
2条回答

您还可以动态生成列表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])

然后按降序排序:

^{pr2}$

然后提取字母并制作一个字典,将加密的字母映射到解密:

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

当你按顺序做replace时,似乎有可能混淆:假设'p'是密码中最常见的字符,你用'e'代替它。稍后,您将替换“e”来替换其他内容,这将再次扰乱您的结果。 我会尝试类似的方法(在您将alpha按您喜欢的方式排序之后):

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

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

相关问题 更多 >