# Function to encrypt the string # according to the morse code chart def encrypt(self, message): message = message.upper() cipher = "" for letter in message: if letter != " ": # Looks up the dictionary and adds the # correspponding morse code # along with a space to separate # morse codes for different characters cipher += self.MORSE_CODE_DICT[letter] + " " else: # 1 space indicates different characters # and 2 indicates different words cipher += " "
return cipher
# Function to decrypt the string # from morse to english def decrypt(self, message): # extra space added at the end to access the # last morse code message += " "
decipher = "" citext = "" for letter in message: # checks for space if letter != " ": # counter to keep track of space i = 0
# storing morse code of a single character citext += letter
# in case of space else: # if i = 1 that indicates a new character i += 1
# if i = 2 that indicates a new word if i == 2:
# adding space to separate words decipher += " " else: # accessing the keys using their values (reverse of encryption) decipher += list(self.MORSE_CODE_DICT.keys())[ list(self.MORSE_CODE_DICT.values()).index(citext) ] citext = ""
return decipher
if __name__ == "__main__": if len(sys.argv) == 1: print("Usage: https://fech.space/morse/encode/hello there") else: from urllib.parse import unquote if sys.argv[1] == "encode": safetext = unquote(sys.argv[2]) print(MorseCoder().encrypt(safetext))