尝试加密和解密文本文件(Python)

2024-06-28 09:53:56 发布

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

此程序正在尝试加密文本文件。它包含不同符号及其对应代码的字典。问题是空格,它不应该将它转换成任何东西,所以它应该像那样保留空格,但程序不读取空格

codes = {
    "A": "%",
    "a": "9",

"B": "@",
"b": "3",

"C": "!",
"c": "1",

"D": "$",
"d": "8",

"E": "^",
"e": "5",

"F": "`",
"f": "4",

"G": "7",
"g": "~",

"H": "(",
"h": "0",

"I": ")",
"i": "2",

"J": "*",
"j": "6",

"K": "-",
"k": "£",

"L": "_",
"l": "¤",

"M": "+",
"m": "¥",

'N': '"',
"n": "¦",

"O": "/",
"o": "§",

"P": "<",
"p": "«",

"Q": ">",
"q": "¬",

"R": "µ",
"r": "{",

"S": "¶",
"s": "}",

"T": "»",
"t": ";",

"U": "|",
"u": "Ø",

"V": "ß",
"v": "=",

"W": "&",
"w": "×",

"X": ",",
"x": "¿",

"Y": ".",
"y": "ä",

"Z": "?",
"z": "¢",
",": "€",
"-": "ð",
".": "Ç",
"1": "ö",
"2": "Д",
"3": "Ж",
"4": "Ђ",
"5": "È",
"6": "À",
"7": "Φ",
"8": "Ψ",
"9": "Ω",
"0": "ö",
" ": " ",
"": ""
}

encrypted = []
read_file = open("file1.txt", "r")

for line in read_file:
    line_list = []
    for ch in line:
        if ch not in codes.keys():
            codes[ch] = str(ch)
            line_list.append(codes[ch.strip()])
        else:
            line_list.append(codes[ch.strip()])
    encrypted.append(line_list)
read_file.close()

write_file = open("new file.txt", "w")
for line in encrypted:
    encrypted_line = "".join(line)
    write_file.write(encrypted_line + "\n")
write_file.close()

read_file = open("new file.txt", "r")

encoded_file = []
for encoded in read_file:
    encoded_list = []
    encoded_list.append(encoded.strip())
    encoded_file.append(encoded_list)
read_file.close()

加密后,程序的这一部分应该从加密文件中读取并解密,然后在屏幕上显示结果。但是单词之间没有空格,因为它在前面的部分中没有转换

read_file = open("new file.txt", "r")

values = list(codes.values())
keys = list(codes.keys())

decrypted_line = ""
for l in encoded_file:
    for l_l in l:
        for ch_l in l_l:
            if ch_l in values:
                index = values.index(ch_l)
                decrypted_line += keys[index]
            # elif ch_l == " ":
            #     decrypted_line += " "

        print(decrypted_line)
        decrypted_line = ""

请帮助解决这个间距问题


Tags: intxtforreadlineopenchcodes