morse code to english python3

Brandon Skerritt picture Brandon Skerritt · Aug 19, 2015 · Viewed 23.6k times · Source

i want to convert Morse Code to English using Python 3+ I have managed to convert english to morse code using this http://code.activestate.com/recipes/578407-simple-morse-code-translator-in-python/

But i want to convert Morse Code to English

I have attempted to do it one charecter at a time, but the problem is that morse code letters are not 1 charecter long like english letters, so E is "." and S is "...", the problem i have is that the dictionary loop will find the "." and match it to E, so instead of getting S i get "E E E" i tried to fix this by detecting spaces and doing it a word at a time, but instead of looking for the letters in the word it searches the entire word against the dictionary i'm new to Python and dictionaries and i don't know how to differeniate between an E "." and an S "..." when searching my dictionary

Here is my code

# defines the dictionary to convert morse to english
CODE_reversed = {'..-.': 'F', '-..-': 'X',
                 '.--.': 'P', '-': 'T', '..---': '2',
                 '....-': '4', '-----': '0', '--...': '7',
                 '...-': 'V', '-.-.': 'C', '.': 'E', '.---': 'J',
                 '---': 'O', '-.-': 'K', '----.': '9', '..': 'I',
                 '.-..': 'L', '.....': '5', '...--': '3', '-.--': 'Y',
                 '-....': '6', '.--': 'W', '....': 'H', '-.': 'N', '.-.': 'R',
                 '-...': 'B', '---..': '8', '--..': 'Z', '-..': 'D', '--.-': 'Q',
                 '--.': 'G', '--': 'M', '..-': 'U', '.-': 'A', '...': 'S', '.----': '1'}


    def main():
        #takes user message and makes it upper case
        msg = input('MESSAGE: ')
        msg = msg.upper()

    addtolist = "" # creates blank string
    message = [] # creates blank list
    for i in msg:
        addtolist = addtolist + i # adds every letter in MSG into a string until it finds a space
        addtolist.upper() # makes every letter uppercase

        if i == " ": # if it detects a space
            message.extend(addtolist)
            # adds the previously created addtolist to a list, this makes one word
            addtolist = "" # clears previous variable

    for i in message:
        # for every word in the list
        str(i) # make it into a string
    print(CODE_reversed[i()]) # search the dictionary for that word


if __name__ == "__main__":
    main()

This code takes a word, and tries to look it up against the dictionary, but it doesn't work i have also tried searching each individual morse code letter against the dictionary but the problem is that you can't tell when a letter starts and ends, so "..." comes out as "EEE" instead of "S" and i don't know how to fix this

i have also tried searching for solutions but have only found them in Java and i do not know Java

Answer

Cory Kramer picture Cory Kramer · Aug 19, 2015

Once you define the mapping in one direction, you can use a dict comprehension to map it the other way

CODE = {'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': '----.' 
        }

CODE_REVERSED = {value:key for key,value in CODE.items()}

Then you can use join with a generator expression to perform the translations.

def to_morse(s):
    return ' '.join(CODE.get(i.upper()) for i in s)

def from_morse(s):
    return ''.join(CODE_REVERSED.get(i) for i in s.split())

>>> to_morse('hello')
'.... . .-.. .-.. ---'
>>> from_morse('.... . .-.. .-.. ---')
'HELLO'