用 ord() 和 chr() 解密凯撒密码?
Decrypting a Caesar Cipher with ord() and 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:”
输出: ” :”
预期输出:“指环王:”
Python 中的 ord() 方法将字符转换为其 Unicode 代码值。 Capital 'A' 从 unicode 65 开始,small '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")
我有一个实验室作业要求我解密一个用凯撒密码加密的输入文件。作为背景,我的导师已经让大家知道密码的移位距离是三。
我能够让我写入输出文件,但我的 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:” 输出: ” :” 预期输出:“指环王:”
Python 中的 ord() 方法将字符转换为其 Unicode 代码值。 Capital 'A' 从 unicode 65 开始,small '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")