凯撒密码仅密码一个字母不完整

时间:2018-10-06 19:03:48

标签: python python-3.x input caesar-cipher

因此,我正在制作一个简单的凯撒密码进行练习,我无法用它来解密整个字符串,而只是单个字母。

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()

我确定解决方案非常简单,仍然可以学习。

对于解决此问题的任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

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 loopsymbol_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

此外,请尝试遵循一个命名约定;您有一个遵循camelCasecleanIt)的函数,另一个遵循snake_casesymbol_add)的函数。尝试以相同的方式命名所有功能。 (Python中的约定是将snake_case用于函数)

答案 1 :(得分:1)

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

查找字典然后.index()进入字符串要快得多。

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

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

基于小写字母,向大写字母添加大写字母映射也很简单:

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