Python 3:使用词典加密

问题描述 投票:-1回答:3

这是我的代码的一部分:

def encrypt_file(file_choice):
    encryption_key = {
"a": 1, "b": 3, "c": 5, "d": 7,"e": 9, "f": 11,"g":        
13, "h": 15, "i": 17, "j": 19,"k": 21, "l": 23, "m": 
25, "n": 27, "o": 29, "p": 31, "q": 33, "r": 35, "s":
 37, "t": 39, "u": 41,"v": 43,"w": 45,"x": 47, "y": 49, "z": 51}

keys = encryption_key.keys()

所以,我在另一个函数中加载了一个文本文件(file_choice)。我希望文本文件中的每个字符,即(a,b,c等)都可以从字典中获得相应的值。

例如,如果文本有单词“和”。我想创建一个for循环,将“和”设置为“1”,将“n”设置为“和”设置为“27”,将“d”设置为“和”设置为“7”。

所以我的主要问题是我无法有效地将文本文件中的字符设置为字典中的相应值。或者更具体地说,我想将文本文件翻译成数字。

任何人都知道如何创建这样的循环?

python python-3.x dictionary encryption
3个回答
0
投票

假设这是一个你想要阅读的有效示例文本,称为text.txt

Hello world, it's a nice day today!

并且你希望将编码的字符写入一个新文件,让我们说newtext.txt。你可以这样做:

d = {
"a": 1, "b": 3, "c": 5, "d": 7,"e": 9, "f": 11,"g":        
13, "h": 15, "i": 17, "j": 19,"k": 21, "l": 23, "m": 
25, "n": 27, "o": 29, "p": 31, "q": 33, "r": 35, "s":
37, "t": 39, "u": 41,"v": 43,"w": 45,"x": 47, "y": 49, "z": 51}

# open to be read file
with open("text.txt", 'r') as file_open:

    # create file to write to
    with open("newtext.txt", 'w') as file_write:
        for line in file_open:

            # encode characters
            new_line = "".join(str(d[c.lower()]) if c.lower() in d else c for c in line)

            # write to file
            file_write.write(new_line)

# open and print contents of file you just wrote to
with open("newtext.txt", 'r') as file_print:
    print(file_print.read())

哪个输出:

159232329 452935237, 1739'37 1 271759 7149 39297149!

注意:您可能需要修改代码才能获得您想要的内容,但这给出了一般的想法。


0
投票

您可以通过char读取char文件并将其作为列表。之后,您可以在新文件中写入chars的值。还要记住,没有关键“空间”的价值。


0
投票

这是获取文件,读取其内容,将每行更改为小写,返回加密输出的函数:

def encrypt_file(file_choice):
    encryption_key = {"a": 1, "b": 3, "c": 5, "d": 7,
                      "e": 9, "f": 11,"g": 13, "h": 15,
                      "i": 17, "j": 19,"k": 21, "l": 23,
                      "m": 25, "n": 27, "o": 29, "p": 31,
                      "q": 33, "r": 35, "s": 37, "t": 39,
                      "u": 41,"v": 43,"w": 45,"x": 47,
                      "y": 49, "z": 51}

    encrypted_txt = ''

    with open(file_choice) as f:
        for line in f:
            for ch in line.lower():
                if ch in encryption_key:
                    encrypted_txt += str(encryption_key[ch])
                else:
                    encrypted_txt += ch

    return encrypted_txt


print(encrypt_file("test.txt")) # 'and' in the text file

1277

>>>
© www.soinside.com 2019 - 2024. All rights reserved.