python解密和加密算法有问题

2024-04-24 03:54:38 发布

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

不知道为什么这不起作用。这应该是加密和解密一个句子。我收到的信是对的,但它们不在正确的位置 秩序

def get_encrypt(original_text,dictionary):
    #4
    match= ""
    for base in original_text:
        match += dictionary[base]
    return match

def rev_look(encrypted_text, dictionary):
    match_key = []

    for key in dictionary:
        i = 0
        for base in encrypted_text:
          print(base)
          if dictionary[key] == base:
            match_key.append(key)
          i += 1
    return match_key


def main():
    print('* Simple Substitution Cipher Tool *')
    #Define the dictionary
    dictionary = {' ':' ','a':'p', 'b':'h', 'c':'q', 'd':'g', 'e':'i', 'f':'u', 'g':'m', 'h':'e', 'i':'a', 'j':'y', 'k':'l', 'l':'n','m':'o', 'n':'f', 'o':'d', 'p':'x', 'q':'j', 'r':'k', 's':'r', 't':'c', 'u':'v', 'v':'s', 'w':'t', 'x':'z', 'y':'w', 'z':'b'}
    #2
    original_text =(input('Please enter the original text: '))
    #3
    encrypted_text = get_encrypt(original_text,dictionary)
    print('The encrypted text is: ', encrypted_text)
    print('The decrypted text is: ', rev_look(encrypted_text,dictionary))


main()

Tags: keytextinforbasegetdictionaryreturn
1条回答
网友
1楼 · 发布于 2024-04-24 03:54:38

由于您首先遍历字典(第一个for循环),所以无法将它们按顺序排列。我稍微修改了一下

def rev_look(encrypted_text, dictionary):
    match_key = []        
    for base in encrypted_text:
        for key in dictionary:
            if dictionary[key] == base:
                match_key.append(key)

    return match_key

注意:当您遍历字典时,不能保证您将按顺序获得元素

相关问题 更多 >