######################################################################## ######################################################################## # # Morse.py # write a function to return the Morse code for a text string # write a function to return the text string for a morse code string # ######################################################################## ######################################################################## # table that defines the ITU morse code standard for letters and numbers morse = { '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' : '--..', '1' : '.----', '2' : '..---', '3' : '...--', '4' : '....-', '5' : '.....', '6' : '-....', '7' : '--...', '8' : '---..', '9' : '----.', '0' : '-----' } # Note: need a single space between letters and a double space between words message = "hello world" def textToMorse(s): """Convert a text string s, containing letters numbers and spaces to Morse code""" code = "" for c in s: #loop over string s one character at a time if c is ' ': code += ' ' # double space between words else: code += morse[c.lower()]+' ' # single space between letters while(code[-1] == ' '): code = code[:-1] # remove last space(s) from message return code def morseToText(s): """Convert a text string s, containing '.','-' and ' ' to text""" # note need iteritems() below if using python2 revMorse = {v: k for k, v in morse.items()} text = "" newS = s.replace(' ',' X ') # indentify double spaces before splitting text sList = newS.split() # split on white space so have each letter and X for spaces for t in sList: if t == 'X': text += ' ' else: text += revMorse[t] return text print('The message is in text "{}"'.format(message)) print('The message is in Morse code "{}"'.format(textToMorse(message))) print('The message is converted back to text "{}"'.\ format(morseToText(textToMorse(message))))