Advertisement
andybeak

Morse code

Sep 14th, 2018
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.24 KB | None | 0 0
  1. CHARACTER_SPACE         = " "
  2. MORSE_WORD_DELIMITER    = "|"
  3. ALPHA_WORD_DELIMTER     = " "
  4. ALPHA_TO_MORSE          = 1
  5. MORSE_TO_ALPHA          = 2
  6.  
  7. codeDictionary = {'A': '.-', 'B': '-...', 'C': '-.-.',
  8.         'D': '-..', 'E': '.', 'F': '..-.',
  9.         'G': '--.', 'H': '....', 'I': '..',
  10.         'J': '.---', 'K': '-.-', 'L': '.-..',
  11.         'M': '--', 'N': '-.', 'O': '---',
  12.         'P': '.--.', 'Q': '--.-', 'R': '.-.',
  13.         'S': '...', 'T': '-', 'U': '..-',
  14.         'V': '...-', 'W': '.--', 'X': '-..-',
  15.         'Y': '-.--', 'Z': '--..',
  16.  
  17.         '0': '-----', '1': '.----', '2': '..---',
  18.         '3': '...--', '4': '....-', '5': '.....',
  19.         '6': '-....', '7': '--...', '8': '---..',
  20.         '9': '----.',
  21.  
  22.         '.': '.-.-.-', ',': '--..--', '?': '..--..',
  23.         '!': '-.-.--', '\'': '.----.', '/': '-..-.',
  24.         '(': '-.--.', ')': '-.--.', '&': '.-...',
  25.         ':': '---...', ';': '-.-.-.', '=': '-...-',
  26.         '+': '.-.-.', '-': '-....-', '_': '..--.-',
  27.         '"': '.-..-.', '$': '...-..-', '@': '.--.-.'
  28.         }
  29.  
  30. def convertWord(word, codeDictionary):
  31.     outputString = ''
  32.     characters = word.split(CHARACTER_SPACE)
  33.     if len(characters) == 1:
  34.         characters = word
  35.     for char in characters:
  36.         char = char.upper()
  37.         try:
  38.           outputString += codeDictionary[char]
  39.         except KeyError, e:
  40.           pass
  41.        
  42.         outputString += CHARACTER_SPACE
  43.     return outputString
  44.  
  45. def convertMessage(message, mode, codeDictionary):
  46.     # if we are decoding morse then swap the keys and values in the dictionary
  47.     if mode == MORSE_TO_ALPHA:
  48.       codeDictionary = dict((v,k) for k,v in codeDictionary.iteritems())
  49.      
  50.     # get a list of words in the message
  51.     if mode == MORSE_TO_ALPHA:
  52.       wordDelimiter = MORSE_WORD_DELIMITER
  53.     else:
  54.       wordDelimiter = ALPHA_WORD_DELIMTER
  55.      
  56.     words = message.split(wordDelimiter)
  57.    
  58.     outputMessage = ""
  59.    
  60.     for word in words:
  61.        outputMessage += convertWord(word, codeDictionary)
  62.        
  63.     return outputMessage
  64.  
  65. mode = ALPHA_TO_MORSE
  66. message ="Hello World"
  67. #mode = MORSE_TO_ALPHA
  68. #message = ".... . .-.. .-.. --- | .-- --- .-. .-.. -.."
  69.  
  70. print(convertMessage(message, mode, codeDictionary))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement