试图解密并打印出我在同一程序中加密的文本文件

2024-04-26 10:34:43 发布

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

所以我终于想出了如何读取和加密文本文件。现在我必须创建第二个程序,打开加密文件,然后在屏幕上显示其解密内容。我一直很好,直到我不得不倒过来,弄清楚如何在字典里打印出键。任何帮助都很好,蒂亚

这是我的密码:

    dictionary = {'A':'D', 'B':'E', 'C':'F', 'D':'G', 'E':'H', 
            'F':'I', 'G':'J', 'H':'K','I':'L',\
            'J':'M', 'K':'N', 'L':'O', 'M':'P', 'N':'Q', 'O':'R', 
            'P':'S', 'Q':'T', 'R':'U',\
            'V':'Y', 'W':'Z', 'X':'A', 'Y':'B', 'Z':'C'}
    def encrypt_file():
        file = open('texttoencrypt.txt', 'r')
        new_file = open('encrypted_text.txt', 'w')

        while True:
            char = file.read(1)
             if not char:
                break
            char = char.upper()
            if char in dictionary.keys():
                 new_char = dictionary[char]
                 new_file.write(new_char)
            else:
                 new_file.write(char)

         file.close()
         new_file.close()

    encrypt_file()

    def decrypt_file():
        encrypted = open('encrypted_text.txt', 'r')
        decrypt = ''
        while True:
            char = encrypted.read(1)
            if not char:
                break
            for key, values in dictionary.items():
                 if char in values:
                     decrypt+= key
                 else:
                     decrypt += char
         print(decrypt)
         encrypted.close()

Tags: textintxtnewclosedictionaryifdef
2条回答

使用列表理解可以反转字典,如下所示: reversed_dictionary = {(v,k) for k,v in dictionary.items()}。这假设您的原始值中没有重复的值,而您的原始值本来就不应该有重复的值。不过,我不知道你说的“在字典里打印出关键字”是什么意思

请注意,您最好使用已经存在的解决方案,即“translate”方法。下面是一个例子,它还发现了您的翻译表的问题:

plain =     'ABCDEFGHIJKLMNOPQRVWXYZ'
scrambled = 'DEFGHIJKLMNOPQRSTUYZABC'

scramble = str.maketrans(plain, scrambled)
descramble = str.maketrans(scrambled, plain)

s1 = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
s2 = s1.translate(scramble)
s3 = s2.translate(descramble)

print("Original:    %s" % s1)
print("Scrambled:   %s" % s2)
print("Descrambled: %s" % s3)

请注意,您当前使用的词典是而不是可逆的。因为字母‘S’、‘T’和‘U’不存在,它们将被隐式映射到它们自身。因此“S”被隐式映射到“S”。但是,字典也会将“P”映射到“S”

如果这个问题已经解决,那么逆转加密的关键点当然是@Boris Lipschitz指出的字典逆转

但是,您的代码不容易支持这一点。为什么?因为你的加密文件方法做的太多了。它打开一个文件,加密并保存一个文件。太多一种方法只能做一件事。考虑这种方法:


def encrypt(content, mapping):
    result = ""
    for char in content:
        char = char.upper()
        if char in mapping.keys():
            new_char = mapping[char]
            result += new_char
        else:
            result += char
    return result


with open('texttoencrypt.txt', 'r') as f:
    content = f.read()
    print(content)
    encrypted = encrypt(content, dictionary)

print(encrypted)

reversed_mapping = {v: k for k, v in dictionary.items()}
decrypted = encrypt(encrypted, reversed_mapping)

print(decrypted)

这几乎就是您的代码,但我将与加密算法无关的所有内容都从encrypt方法中移出。现在它可以很容易地重复使用解密!(您可以通过编写result += mapping.get(char, char)来进一步改进这一点,但我希望与您的原始代码保持接近

然而,Boris Lipschitz的论点是完全正确的:不要重新发明轮子。只需使用maketrans/transform解决方案:)

相关问题 更多 >