解码赋值python

2024-05-18 10:16:51 发布

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

我们的任务是获取一个包含密码密钥的密钥txt文件,将其应用于加密文本文件以生成解密文件。你知道吗

我似乎无法解密。任何帮助都将不胜感激!你知道吗

    keycode = {}

def key(filename):
    with open("key.txt", "r") as infile:   
        for line in infile:
            parts = line.split()
            plain = parts[0]
            code = parts[1]
            keycode[plain] = code

        return keycode

key("key.txt")


decrypted_text = []
with open ("encrypted.txt" , "r")as infile:
        for c in infile:
            if c in keycode:
                c = keycode[1]
            decrypted_text.append(c)

with open("decrypted.txt" , "w") as outfile:
      for line in decrypted_text:
          outfile.write(line)


print "Decrypted.txt has been written."

Tags: 文件keytextintxtforaswith
1条回答
网友
1楼 · 发布于 2024-05-18 10:16:51

第一个问题是for c in infile:。您不是在string上迭代,而是在file上迭代。要获取file的内容,需要调用File.read()方法。你知道吗

第二个问题是keycode[1],它获取keycode字典的第一个元素,不管它的内容是什么。keycode[c]是正确的方法。你知道吗

with open ("encrypted.txt" , "r") as infile:
    for c in infile.read():
        if c in keycode:
            c = keycode[c]
        decrypted_text.append(c)

这就是密钥文件的外观:

i h
p o
m l
z y

i替换为hp->;o等等。请记住,字典索引是区分大小写的,因此Hh不同。同样,您在一个文件上迭代,在本例中,您需要在key()方法中使用File.readlines()方法。你知道吗

相关问题 更多 >