凯撒密码,Python 3,新程序员

2024-04-28 15:03:14 发布

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

第一次投递到Stackoverflow

我是一名新的程序员,所以请容忍我,因为我还没有掌握所有可能的函数的最新知识,所以可能是我目前缺少一种能够快速解决问题的函数或方法的知识

我正在尝试制作一个Python3脚本,它可以解密使用caesar密码的加密文本。 我现在已经这样做了,所以我的代码将加密文本与字母表的字符串进行比较,然后存储最常见的3个字母。出于某种原因,标点符号在这里不是问题

当需要解密文本时,程序无法通过任何标点符号。 它通过移动字母表使最常见的字母变成“E”来减少字母数。我无法找到一种方法让python忽略并打印标点符号。我已经制作了一个单独包含标点符号的字符串,但我不知道接下来要做什么。 代码附在下面的Python 3中

感谢大家的帮助

#string used for comparing code to
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

#strings for shifting the code
shift = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
punctuation = ".,!;:?"

#ask user for the encrypted text
code = input("Enter text: ")

#variables storing the most common letters and the # of times they come up
common1 = 0
common2 = 0
common3 = 0
ac = 0
bc = 0
cc = 0

for i in range(0, len(alphabet)):
    # print number of times each letter comes up --- print( str(alphabet[i]) + " is present " + str(code.count(alphabet[i])) + " number of times" )

    #finding the number of times the most common letter comes up
    if code.count(alphabet[i]) > common1:
        common3 = common2
        cc = bc
        common2 = common1
        bc = ac
        common1 = code.count(alphabet[i])
        ac = alphabet[i]

    elif code.count(alphabet[i]) > common2:
        common3 = common2
        cc = bc
        common2 = code.count(alphabet[i])
        bc = alphabet[i]

    elif code.count(alphabet[i]) > common3:
        common3 = code.count(alphabet[i])
        cc = alphabet[i]


print("Most common letter, " + str(ac) + ", comes up " + str(common1) + " times")
print("Second most common letter, " + str(bc) + ", comes up " + str(common2) + " times")
print("Third most common letter, " + str(cc) + ", comes up " + str(common3) + " times")


for i in range(0, len(code)):
    a = shift.index("E") + 26 - shift.index(ac)
    print(shift[a + shift.index( code[i] ) ], end = "")

Tags: theforshiftcountcodecommonprintbc
1条回答
网友
1楼 · 发布于 2024-04-28 15:03:14

您应该检查每个位置的代码值是否在字母表中。如果不是,只打印代码中的值并继续下一个循环


for i in range(0, len(code)):
    if code[i] not in alphabet:
        print(code[i])
        continue
    a = shift.index("E") + 26 - shift.index(ac)
    print(shift[a + shift.index( code[i] ) ], end = "")

相关问题 更多 >