使用ord()和chr()解密Caesar密码?

2024-09-30 18:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个实验室的任务,要求我解密一个用ceasar密码加密的输入文件。作为背景,我的导师已经让每个人都知道密码的移位距离是三

我能够让我的文件写入输出文件,但我的output.txt完全不可读,与预期的输出根本不接近。我记得我的导师提到我们可以使用ord()和chr()结合算术将编码字符转换为纯文本

decode = inpf.readlines()
for line in decode:
    output = ""
    c = str()
    for c in line:
        if c >= "a" and c <= "z":
            x = ord(c)
            x += 23
            x %= 26
            y = chr(x)
            output = output + y
        if c >= "A" and c <= "Z": 
            x = ord(c)
            x += 23
            x %= 26
            y = chr(x)
            output = output + y
        else:
            output = output + c

    outf.write(output + "\n")

我感谢你能提供的任何帮助或建议!谢谢

编辑: 样本输入:“Wkh Orug Ri Wkh Ulqjv:” 输出:“ 预期输出:“魔戒”:


Tags: and文件in密码foroutputifline
1条回答
网友
1楼 · 发布于 2024-09-30 18:31:27

Python中的ord()方法将字符转换为其Unicode代码值。大写字母“A”从unicode 65开始,小写字母“A”从unicode 97开始。此外,还应使用“elif”而不是第二个“if”语句。否则,如果是小写字母,该字母将重复。您需要获取字母在字母表中的位置,应用移位并将其转换回unicode。下面给出了代码的工作示例:

inpf = open("input.txt",'r')
outf = open("output.txt",'w')

decode = inpf.readlines()
for line in decode:
    output = ""
    c = str()
    for c in line:
        if c >= "a" and c <= "z":
            x = ord(c) - 97 #small a
            x -= 3
            x = (x+26)%26 #For handling negative numbers
            y = chr(x + 97)
            output = output + y
        elif c >= "A" and c <= "Z": 
            x = ord(c) - 65 #Capital A
            x -= 3
            x = (x+26)%26 #For handling negative numbers
            y = chr(x + 65)
            output = output + y
        else:
            output = output + c

    outf.write(output + "\n")

相关问题 更多 >