首页 > 解决方案 > Python 凯撒密码脚本

问题描述

# Paste the text you want to encipher (or decipher)
original = input("Original text: W fowgsr am roiuvhsf wb hvs Oasfwqob")

# Declare (or guess) the offset. Positive or negative ints allowed
offset = int(input("Offset: 12"))

ciphered = ''

for c in original:
    c_ascii = ord(c)

    if c.isupper():
        c = chr((ord(c) + offset - ord('A')) % 26 + ord('A'))
    elif c.islower():
        c = chr((ord(c) + offset - ord('a')) % 26 + ord('a'))

    ciphered += c

# makes a new file, caesar.txt, in the same folder as this python script
with open("caesar.txt", 'w') as f:
    f.write(ciphered)

""" 这是我们老师用来帮助我们解密 Caeser Cyphers 的一些代码,但是由于某种原因,我仍然将输入作为输出,对于为什么这不起作用的任何想法?老师确认它有效。 """ """ 这个例句的 12 个字符的移位是“我在美国养育了我的女儿”(我需要它对大小写敏感。) - 此代码还将解密更多具有相同移位 12 的句子"""

标签: pythonencryption

解决方案


我对这个问题有点困惑,所以这个答案可能是错误的,但如果你想解码消息,只需将偏移前的 + 交换为 - (对于每种情况)。你应该最终得到这个:

# Paste the text you want to encipher (or decipher)
original = input("Original text: W fowgsr am roiuvhsf wb hvs Oasfwqob")

# Declare (or guess) the offset. Positive or negative ints allowed
offset = int(input("Offset: 14"))


ciphered = ''

for c in original:
    c_ascii = ord(c)

if c.isupper():
    c = chr((ord(c) - offset - ord('A')) % 26 + ord('A'))
elif c.islower():
    c = chr((ord(c) - offset - ord('a')) % 26 + ord('a'))

ciphered += c

# makes a new file, caesar.txt, in the same folder as this python script
with open("caesar.txt", 'w') as f:
    f.write(ciphered)

这将解码消息,您可以在计算机询问用户是编码还是解码时添加一个选项。请告诉我这是否是您正在寻找的内容,如果您需要,我很乐意尝试多次查看代码。


推荐阅读