首页 > 解决方案 > 用 ord() 和 chr() 解密凯撒密码?

问题描述

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

我能够让我写入输出文件,但我的 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:”输出:“:”预期输出:“指环王:”

标签: pythondecodingcaesar-cipher

解决方案


Python 中的 ord() 方法将字符转换为其 Unicode 代码值。大写“A”从 unicode 65 开始,小写“a”从 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")

推荐阅读