I have this ceasar cipher decryption programme below:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
text_input = input('Enter text: ')
possible_keys = len(alphabet)
for keys in range(possible_keys):
decrypted_text = ''
for character in text_input:
if character in alphabet:
position = alphabet.find(character)
possible_pos = position - keys
possible_pos %= len(alphabet)
new_character = alphabet[possible_pos]
decrypted_text += new_character
else:
decrypted_text += character
print(f' Key#:{keys}: {decrypted_text}')
path = r'C:UsersthongOneDriveDocumentswords_alpha.txt'
with open(words_alpha, "r") as file:
word_list = [line.strip() for line in file]
# Check if any word in decrypted_text matches the words from the file
for word in decrypted_text.split():
if word.lower() in word_list:
print(f"'{word}' is a valid word!")
else:
print(f"'{word}' is not found.")
The programme is intended to automatically look for the specific key that was used to encrypt the ceasar cipher. I have made it so the programme check whether which “decrypted_text” outputs have valid english words, using a .txt file; then determine the key output that contains the most valid words. However the programme only ultilised the last output of “decrypted_text” and therefore is unable to look for the right key.
I have only started Python for a couple months, I applogize if there is any confusion!
Minh Thong NGUYEN is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
6
That happens because in every iteration decrypted_text
sets to an empty string and don’t save. So you can add list of decrypted_text and append a new value to that list.
After you can iterate on that list, to check if any of decrypted text is valid.
Every time after you print your decrypted_text
you should append your decrypted_text
to a list and then later on in your last for loop
you should iterate over your list of decrypted_text
. That way it will solve your problem.
PS: I guess its a very rare chance that any of the decrypted_text
will have any valid words….