Use the dictionary of Morse code symbols given in the file morse.py to write a program which can translate a message to and from Morse code, using spaces to delimit individual Morse code "letters" and slashes ('/'
) to delimit words. For example, 'PYTHON 3'
becomes '.--. -.-- - .... --- -. / ...--'
.
The provided dictionary only provides a mapping from the alphanumeric characters to Morse code, so to translate from Morse code, we need the reverse dictionary, revmorse, which we set up in the first loop of the code below.
The two functions of code translate to and from Morse code, catching any unidentified characters and outputting them as asterisks.
from morse import morse
revmorse = {}
for k,v in morse.items():
revmorse[v] = k
def msg_to_morse(msg):
morse_msg = []
for c in msg.upper():
if c == ' ':
morse_msg.append('/')
else:
try:
morse_msg.append(morse[c])
except KeyError:
morse_msg.append('*')
return ' '.join(morse_msg)
def morse_to_msg(msg):
decoded_msg = []
for word in morse_msg.split('/'):
decoded_word = []
for c in word.split(' '):
if c:
try:
decoded_word.append(revmorse[c])
except KeyError:
decoded_word.append('*')
decoded_word = ''.join(decoded_word)
decoded_msg.append(decoded_word)
return ' '.join(decoded_msg)
msg = 'My hovercraft is full of eels!'
morse_msg = msg_to_morse(msg)
decoded_msg = morse_to_msg(morse_msg)
print(morse_msg)
print(decoded_msg)
The output, using the example message in the code is:
-- -.-- / .... --- ...- . .-. -.-. .-. .- ..-. - / .. ... / ..-. ..- .-.. .-.. / --- ..-. / . . .-.. ... *
MY HOVERCRAFT IS FULL OF EELS*