Caesar Cipher code only Ciphers 一个字母而不是整个字符串

Caesar Cipher code only Ciphers one letter not entire string

所以我正在制作一个简单的凯撒密码用于练习,但我无法用它来破译整个字符串,只能破译单个字母。

symbol_add 是有问题的函数。

代码如下:

import re

alphabet = "abcdefghijklmnopqrstuvwxyz"

def cleanIt(clean):
    global alphabet
    s = re.sub('[^a-z]+', '?', str(clean))
    return s

def symbol_add(symbol, key):
    encryptedMsg = ""
    for x in symbol:
        position = alphabet.find(x)
        newPosition = (position + key) % 26
        newLetter = alphabet[nyPosisjon]

    encryptedMsg += nyBokstav
    return encryptedMsg

def cipher(data,key):
    text = ""
    if data in alphabet:
        text += symbol_add(symbol=data,key=key)
        return text

def main():
    try:
        msg = (input("Write the message you would like to encrypt\n"))
        key = int(input("which key would you like to use?\n"))
        cleanIt(clean=msg)
        print(cipher(data=msg, key=key))
    except ValueError:
        print("Write a number!")

main()

我确定解决方案非常简单,仍在学习中。

如能提供解决此问题的任何帮助,我们将不胜感激!

import re

alphabet = "abcdefghijklmnopqrstuvwxyz"

def cleanIt(clean):
    global alphabet
    s = re.sub('[^a-z]+', '?', str(clean))
    return s

def symbol_add(symbol, key):
    position = alphabet.find(symbol)
    newPosition = (position + key) % 26
    newLetter = alphabet[newPosition]
    return newLetter

def cipher(data,key):
    text = ""
    for letter in data:
        if letter in alphabet:
            text += symbol_add(symbol=letter,key=key)
    return text

def main():
    try:
        msg = (input("Write the message you would like to encrypt\n"))
        key = int(input("which key would you like to use?\n"))
        # Note: you need to assign msg to be equal to cleanIt(clean=msg). 
        #       Just calling cleanIt(clean=msg) won't work, as strings 
        #       are immutable in Python
        msg = cleanIt(clean=msg)
        print(cipher(data=msg, key=key))
    except ValueError:
        print("Write a number!")

main()

主要变化是:

  • for loop 已从 symbol_add 移动到 cipher,因此每个字符 symbol_add 都会被调用
  • main()中:cleanIt(clean=msg) -> msg = cleanIt(clean=msg);这样做的原因是字符串在 Python 中是不可变的,这意味着您需要重新分配变量 msg 以实质上指向新字符串。

此代码的输出:

Write the message you would like to encrypt
test
which key would you like to use?
1
uftu

另外,尽量坚持单一的命名约定;您有一个函数在 camelCase (cleanIt) 之后,另一个函数在 snake_case (symbol_add) 之后。尝试以相同的方式命名所有函数。 (Python中的约定是函数使用snake_case

如果在输入方法时填入字典作为查找,则可以大大简化您的密码方法。它包含基于提供的 key 的映射,并将您的输入字符映射到密码字符。

在字典中查找比 .index() 到字符串中查找要快得多。

使用 dict.get(key[,default]) 允许为未知数提供 '?',因此您不需要 import re 也不需要预处理。

了解 dict.get()Why dict.get(key) instead of dict[key]?

在小写映射的基础上,将大写映射添加到 chiffre 也很简单:

alphabet = "abcdefghijklmnopqrstuvwxyz"

def cipher(data, key):
    # in case you change alphabet
    la = len(alphabet)

    # get the default lookup 
    chiffre = { c:alphabet[(i+key)%la] for i,c in enumerate(alphabet) }

    # create lookup for upper cases as well
    chiffre.update( { c.upper():n.upper() for c,n in chiffre.items() } )

    # supply ? for all unknowns, use the knowns where possible and return as string
    return ''.join( (chiffre.get(c,"?") for c in data) )

def main():
    try:
        msg = (input("Write the message you would like to encrypt\n"))
        key = int(input("which key would you like to use?\n"))

        print(cipher(data=msg, key=key))
    except ValueError:
        print("Write a number!")

main()

输出:

Write the message you would like to encrypt
Hello World
which key would you like to use?
1
Ifmmp?Xpsme