Вы должны создать словарь, чтобы найти для каждой зашифрованной записи символа соответствующий перевод.
## Create an empty dictionary
your_dictionary = {}
## Fill your_dictionary with the (key, values) couples
## With keys your key list, and values your values list
for key, value in zip(keys, values):
your_dictionary[key] = value
## Decrypt your encrypted message
## With enc_message the encrypted message
decrypted_message = ""
for c in enc_message:
decrypted_message = decrypted_message+your_dictionary[c]
Теперь вы можете захотеть воспроизвести его немного безопаснее, поскольку вы можете столкнуться с некоторыми проблемами, если попытаетесь расшифровать символ, который вы не добавили в качестве ключа в словаре, или пробел.
decrypted_message = ""
for c in enc_message:
if c.isspace():
decrypted_message = decrypted_message + c
elif c not in your_dictionary :
## Handle this case how you want. By default you can add it.
decrypted_message = decrypted_message + c
else :
decrypted_message=decrypted_message + your_dictionary[c]
Таким образом, поскольку вы запрашивали зашифрованное и дешифрованное сообщение, которое должно исходить из файла и выводиться в виде файла, вы можете использовать следующие функции и инструкции для выполнения всего цикла:
## Decrypt a message with a specific dictionary
def decrypt_message(message, your_dict):
decrypted_message = ""
word = ""
for index, c in enumerate(enc_message):
print(c)
if c.isspace():
decrypted_message = decrypted_message + c
elif c not in your_dict :
decrypted_message = decrypted_message + c
else :
decrypted_message = decrypted_message + your_dict[c]
return decrypted_message
## Populate a dictionary with the given couples
def populate_dictionary(keys, values):
your_dictionary = {}
for key, value in zip(keys, values):
your_dictionary[key] = value
return your_dictionary
## Example keys
keys = ['a', 'b', 'c']
## Example values
values = ['d', 'e', 'f']
## Open the input file
with open('encryptedMessage.txt', 'r') as file:
enc_message = file.read().replace('\n', '')
## Populating the dictionary
dic = populate_dictionary(keys, values)
## Decrypting the message
dec_message = decrypt_message(enc_message, dic)
## Creating and saving the decrypted message in the output file.
text_file = open("decryptedMessage.txt", "w")
text_file.write(dec_message)
text_file.close()