Search code examples
pythonencryptioncryptographycaesar-cipher

Python Caesar Cipher project, incorrect output


I can't seem to get this program I'm supposed to do for a project to output the correct output, even though I have tried getting it to work multiple times. The project is:

Your program needs to decode an encrypted text file called "encrypted. txt". The person who wrote it used a cipher specified in "key. txt". This key file would look similar to the following:

A    B 
B    C 
C    D 
D    E 
E    F 
F    G 
G    H 
H    I 
I    J 
J    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    A 

The left column represents the plaintext letter, and the right column represents the corresponding ciphertext. Your program should decode the "encrypted.txt" file using "key.txt" and write the plaintext to "decrypted.txt". Your program should handle both upper and lower case letters in the encrypted without having two key files (or duplicating keys).  You may have the decrypted text in all caps. You should be able to handle characters in the encrypted  text that are not in your key file.  In that case, just have the decryption repeat the character.  This will allow you to have spaces in your encrypted text that remain spaces when decrypted. While you may write a program to create the key file - do NOT include that in the submission.  You may manually create the encrypted and key text files.  Use either the "new file" option in Python Shell (don't forget to save as txt) or an editor such as notepad.  Do not use word.

Here is my code:

keyFile = open("key.txt", "r")
keylist1= []
keylist2 = []

for line in keyFile:
  keylist1.append(line.split()[0])
  keylist2.append(line.split()[1])
keyFile.close()
encryptedfile = open("encrypted.txt", "r")
lines = encryptedfile.readlines()
currentline = ""
decrypt = ""
for line in lines: 
  currentline = line
  letter = list(currentline)
  for i in range(len(letter)):
    currentletter = letter[i]
    if not letter[i].isalpha():
      decrypt += letter[i]
    else:
      for o in range(len(keylist1)):
        if currentletter == keylist1[o]:
          decrypt += keylist2[o]
print(decrypt)

The only output I get is:

, ?

which is incorrect.


Solution

  • You forgot to handle lowercase letters. Use upper() to convert everything to a common case.

    It would also be better to use a dictionary instead of a pair of lists.

    mapping = {}
    with open("key.txt", "r") as keyFile:
        for line in keyFile:
            l1, l2 = line.split()
            mapping[upper(l1)] = upper(l2)
    decrypt = ""
    with open("encrypted.txt", "r") as encryptedFile:
        for line in encryptedFile:
            for char in line:
                char = upper(char)
                if char in mapping:
                    decrypt += mapping[char]
                else:
                    decrypt += char
    print(decrypt)