Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Oliver Schuller
- def encrypt(msg, n):
- encryptedText = ""
- # Make a "for loop" that will convert string to ascii, shifts character n positions and then convert back to
- # normal characters
- for letter in range(len(msg)):
- if ord(msg[letter]) < 97 or ord(msg[letter]) > 122: # Leaves characters outside the alphabet unchanged
- encryptedText += chr(ord(msg[letter]))
- elif ord(msg[letter]) - n < 97: # If the ascii number is less than 97, add 26 so it stays within the alphabet
- encryptedText += chr(ord(msg[letter]) - n + 26)
- else:
- encryptedText += chr(ord(msg[letter]) - n) # Shifts character n positions
- return encryptedText
- def decrypt(msg, n):
- clear_msg = ""
- # Make a "for loop" that will convert string to ascii, shifts character n positions and then convert back to
- # normal characters
- for letter in range(len(msg)):
- if ord(msg[letter]) < 97 or ord(msg[letter]) > 122: # Leaves characters outside the alphabet unchanged
- clear_msg += chr(ord(msg[letter]))
- elif ord(msg[letter]) + n > 122:
- clear_msg += chr(ord(msg[letter]) + n - 26) # If the ascii number is greater than 122, subtract 26 so it
- # stays within the alphabet
- else:
- clear_msg += chr(ord(msg[letter]) + n) # Shifts character n positions
- return clear_msg
- def lfa(msg):
- count = {}
- for i in msg:
- if ord(i) < 97 or ord(i) > 122: # Skip characters outside the alphabet
- continue
- elif i in count: # If the letter already is in count, increment 1
- count[i] += 1
- else: # Otherwise add the letter as a key and 1 as value
- count[i] = 1
- for letter, occurrence in count.items(): # Print how many times each letter occurs
- print('Character {} occurs {} times'.format(letter, occurrence))
- print("Choose your option: \n 1. Encrypt message \n 2. Decrypt message \n 3. Read and write to file \n "
- "4. Letter frequency analysis \n")
- choice = input("Write the number for your option: ")
- if choice == "1":
- message = input("Enter your text here: ")
- message = message.lower()
- key = int(input("Enter your key here (1-25): "))
- print(encrypt(message, key))
- elif choice == "2":
- message = input("Enter your text here: ")
- message = message.lower()
- key = int(input("Enter your key here (1-25): "))
- print(decrypt(message, key))
- elif choice == "3":
- f1 = open("clearText.txt", "r")
- lines = f1.readlines()
- message = ""
- for line in lines:
- message += line
- message = message.replace("\n", " ")
- key = int(input("Enter your key here (1-25): "))
- f2 = open("encryptedText.txt", "a")
- lines = f2.write(encrypt(message, key))
- elif choice == "4":
- text = input("Write your text here: ")
- text = text.lower()
- lfa(text)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement