python - 用 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:”输出:“:”预期输出:“指环王:”
解决方案
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")
推荐阅读
- python - python-lzw 不解压缩较大的 blob
- python - opname 如何/在哪里填充?
- amazon-s3 - 使用邮递员的 AWS S3 预签名 URL 上传图像
- javascript - Reactjs - 列表中自定义组件的键
- mysql - mySQLi 检查 parent_category 是否匹配 category_id = 0
- java - 关于 WorkManager 的 WorkerResult 的 RETRY 值
- javascript - FullCalendar 重复事件无法正常工作
- office-js - Outlook 加载项:Office.js 和 Rest API 之间的用户名不匹配
- sql - 在 SELECT 中使用 CASE 分组
- reactjs - 尝试构建生产时出现在 create-react-app 中的“无法缩小此文件中的代码”