I want to write a function called lazy_encrypt. The input dictionary is a mapping of characters: character pairs it should use to "encrypt" the contents of the input file before writing it to the output file.
If the character is a key in the dictionary, then lazy_encrypt should write the value associated with that key to the output file. If it is not a key, it should write the original character.
It seems to work fine with below example, however, I got an KeyError: 'P' for another example. I have used the "if ..." statement to check if the key is in the dictionary, why is this still happening with my code?
The contents of anIutputFile.txt
#Here is a pretty simple message to encrypt
#When it's encrypted, it will look different
the contents of anOutputFile.txt after running will be:
#Horo is a protty simplo mossago ta oncrypt
#Whon it's oncryptod, it will laak difforont
#Write your function here!
def lazy_encrypt(string1, string2, a_dictionary):
f = open(string2) # open the file
o = open(string1,'w')
for line in f: # iterate over the file line by line
words = line.split() # word list
result = []
save_to_file = ''
for word in words:
new_word = ''
for c in word:
if c.lower() in a_dictionary:
c = a_dictionary[c]
#print(c)
new_word += c
result.append(new_word)
save_to_file = ' '.join(result)
o.write(save_to_file)
o.write('\n')
o.close()