CHARACTER_SPACE = " " MORSE_WORD_DELIMITER = "|" ALPHA_WORD_DELIMTER = " " ALPHA_TO_MORSE = 1 MORSE_TO_ALPHA = 2 codeDictionary = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '.': '.-.-.-', ',': '--..--', '?': '..--..', '!': '-.-.--', '\'': '.----.', '/': '-..-.', '(': '-.--.', ')': '-.--.', '&': '.-...', ':': '---...', ';': '-.-.-.', '=': '-...-', '+': '.-.-.', '-': '-....-', '_': '..--.-', '"': '.-..-.', '$': '...-..-', '@': '.--.-.' } def convertWord(word, codeDictionary): outputString = '' characters = word.split(CHARACTER_SPACE) if len(characters) == 1: characters = word for char in characters: char = char.upper() try: outputString += codeDictionary[char] except KeyError, e: pass outputString += CHARACTER_SPACE return outputString def convertMessage(message, mode, codeDictionary): # if we are decoding morse then swap the keys and values in the dictionary if mode == MORSE_TO_ALPHA: codeDictionary = dict((v,k) for k,v in codeDictionary.iteritems()) # get a list of words in the message if mode == MORSE_TO_ALPHA: wordDelimiter = MORSE_WORD_DELIMITER else: wordDelimiter = ALPHA_WORD_DELIMTER words = message.split(wordDelimiter) outputMessage = "" for word in words: outputMessage += convertWord(word, codeDictionary) return outputMessage mode = ALPHA_TO_MORSE message ="Hello World" #mode = MORSE_TO_ALPHA #message = ".... . .-.. .-.. --- | .-- --- .-. .-.. -.." print(convertMessage(message, mode, codeDictionary))