Home > Back-end >  Leaving punctuations untouched during Caesar Cipher in python
Leaving punctuations untouched during Caesar Cipher in python

Time:11-21

I read multiple related threads about how to solve the same problem, but I couldn't apply the solutions to my code.

Also, the code is supposed receive a path to a text file which must contain text composed of only English letters and punctuation symbols and a destination file for encrypted data.

Any suggestions?

    def check_alpha(m_string):
        list_wanted = ['!', '?', '.', ',', ' ']
        for letter in m_string:
            if not (letter in list_wanted or letter.isalpha()):
                 return False

            return True and any(letter.isalpha() for letter in m_string)

    while True:
       string = input("Enter the text to be encrypted: ")
       if check_alpha(string):
        break
       else:
          print("Please enter a valid text: ")
       continue
    while True:  #  Validating input key
        key = input("Enter the key: ")
        try:
            key = int(key)
        except ValueError:
            print("Please enter a valid key: ")
            continue
        break
    
    
    def caesarcipher(string, key):   #  Caesar Cipher
        encrypted_string = []
        new_key = key % 26
        for letter in string:
            encrypted_string.append(getnewletter(letter, new_key))
        return ''.join(encrypted_string)
    
    
    def getnewletter(letter, key):
        new_letter = ord(letter)   key
        return chr(new_letter) if new_letter <= 122 else chr(96   new_letter % 122)
    
    
    with open('Caesar.txt', 'a') as the_file:  # Writing to a text file
        the_file.write(caesarcipher(string, key))
    
    print(caesarcipher(string, key))
    print('Your text has been encrypted via Caesar-Cipher, the result is in Caesar.txt')


CodePudding user response:

As mentioned by Alex P you can simple handle all punctuation separately with a if condition:

def caesarcipher(string, key):   #  Caesar Cipher
        encrypted_string = []
        new_key = key % 26
        for letter in string:
            if letter in ['!', '?', '.', ',', ' ']:
                encrypted_string.append(letter)
            else:
                encrypted_string.append(getnewletter(letter, new_key))
        return ''.join(encrypted_string)

CodePudding user response:

A simple example of the Ceaser Cipher tailed for your need

def encrypt(text,s):
  result = ""
  # transverse the plain text
  for i in range(len(text)):
    char = text[i]
    # Encrypt uppercase characters in plain text
    if is_a_letter(char):
    
      if (char.isupper()):
        result  = chr((ord(char)   s-65) % 26   65)
        # Encrypt lowercase characters in plain text
      else:
        result  = chr((ord(char)   s - 97) % 26   97)
    else:
      result  = char
  return result
#check the above function
text = "CEASER!CIPHER.DEMO"
s = 4 # the length of the shift 
my_list = ['!', '?', '.', ',', ' ']

# check if the character is one of the above list
def is_a_letter(text):
  for x in range(0,len(my_list)):
    if text == my_list[x]:
      return False
  return True

print("Plain Text : "   text)
print("Shift pattern : "   str(s))
print("Cipher: "   encrypt(text,s))

CodePudding user response:

Well you can make another function which can relate to check_alpha() function.

EDIT: I hope I understand your problem correctly. If not then let me know.

def load_file(file_path)
   from pathlib import Path
   
   if not Path(file_path).exist():
      return False
   
   with open(file_path, 'r') as fin:
      for line in fin.readlines():
           if not check_alpha(line.strip('\n')):
              return False

   return fin.read() -> this will create '\n' at every end of the line! keep that in mind

def check_aplha(m_string).... -> keep the original

while True:
   file_path = input("Enter file path with text selected for encryption: ")
   string = load_file(file_path)
      if string: -> everything which is not None, Empty, False or 0 is True
         break
      else:
         print("Please enter a valid file with only valid letters/punctuations.\n")
         continue

In this way exactly you can do it for encrypted data. I guess all rules apply either on encrypted either on decrypted data.

  • Related