How to Write a Morse Code Translator in Python

Originally posted on makeuseof.

Practice string translation with this easy-to-follow tutorial.

Morse code has existed since the early 1800s and has found its way to the digital era. From serving as a critical medium of communication during the Second World War to sending encrypted messages in aviation, and marine, Morse code is here to stay.

If you are unaware of this fascinating language, get ready to not only discover Morse code but also build your very own translator using Python.

What Is Morse Code?

Morse code is a method of communication in which you encode text characters into a standard sequence of two signals of varying duration, denoted by dots and dashes. The Morse code gets its name from Samuel Morse, one of the inventors of the telegraph. You can memorize it and transmit it via sound waves or visible light perceivable by the human senses.

The length of the Morse code equivalent is inverse to our frequency of usage of that alphabet, and you can see that Morse code assigns the most common letter in the English language, E, to just a dot.

You can use these free Morse code software and apps to send coded messages to one another. On the other hand, learning Morse code is fairly simple, and you can learn it within a month with a fair amount of practice. To help you get started, here are nine sites to learn Morse code for free.

How to Build Morse Code Translator Using Python

Start by defining a Python dictionary named MORSE_CODE_DICT to store the Morse code values. The keys will be letters of the English alphabet, with the appropriate dot or dash sequence as the corresponding value. Using a dictionary, you can quickly look up any key to its corresponding value.

MORSE_CODE_DICT = { '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':'-----', ', ':'--..--', '.':'.-.-.-',
                    '?':'..--..', '/':'-..-.', '-':'-....-',
                    '(':'-.--.', ')':'-.--.-' }

Declare a function named encrypt that accepts message as an input parameter. Inside the function, initialize a variable named cipher with an empty string. You’ll use this to create and store the encrypted message. Next, declare a for loop that iterates over each letter in the message.

If the letter is not white space, pass it to the dictionary for lookup. The dictionary returns the corresponding More code value based on the key. Add a space to separate the characters of the Morse code and use the shorthand += operator to concatenate it with the code obtained from the dictionary. If the letter is a white space, add an extra space to the cipher; Morse code separates words with two consecutive spaces.

def encrypt(message):
    cipher = ""
    for letter in message:
        if letter != " ":
            cipher += MORSE_CODE_DICT[letter] + " "
        else:
            cipher += " "
    return cipher

Declare a function named decrypt that accepts message as an input parameter. Add a space at the end, using the shorthand operator to access the last character of the Morse code. Initialize two variables, decipher, and citext to hold empty strings. The decipher variable will hold the decrypted sentence consisting of the English alphabet while you use citext to store each letter of the Morse code.

Iterate a for loop that runs through each letter of the Morse code. If the letter is not white space, initialize a counter variable i that keeps track of the number of spaces to zero and store the Morse code of a single character in citext. Otherwise, the letter is a space, so increment the counter by one.

If the counter equals two, it means you have to add white space to the decrypted word variable decipher. Otherwise, access the keys using their values. To do this, iterate over the key-value pairs in dictionary using the items function. If the citext equals the value, add the corresponding key to the decipher variable using the shorthand operator.

Finally, clear the citext to get the next letter and return the decrypted sentence obtained to the function call.

def decrypt(message):
    message += " "
    decipher = ""
    citext = ""

    for letter in message:
        if letter != " ":
            i = 0
            citext += letter
        else:
            i += 1

            if i == 2:
                decipher += " "
            else:
                for key, value in MORSE_CODE_DICT.items():
                    if citext == value:
                        decipher += key

                citext = ""

    return decipher

Test the functions with some sample input. Start by initializing a variable named message with the word or sentence you want to encrypt. Use the upper function to convert all the letters to upper case and pass it to the encrypt function as an argument. Morse code contains only uppercase letters, which are the keys in the dictionary. This also helps avoid unnecessary runtime checks for valid case.

Print the resulting value to view the Morse code equivalent of the original sentence.

Then, store a Morse code in the message variable and pass it to the decrypt function. Print the result and check that it’s correct.

Instead of hardcoding the input, you can accept it from the user with the input() function.

message = "Make Use Of"
result = encrypt(message.upper())
print(result)

message = "-- .- -.- . ..- ... . --- ..-."
result = decrypt(message)
print(result)

Output of Morse Code Translator in Python

The Python program translates each letter of the English alphabet to its Morse code equivalent and displays it to the terminal output screen as shown. If you copy the output obtained and pass it for decryption you will receive the original text that you passed in earlier. This verifies that the translation worked perfectly.

Output of Morse Code Translator in Python

Mobile Applications for Morse Code

Morse code translators are available for free right at your fingertips. More than hundreds of applications such as Morse Mania, Morse Trainer, Morse Code Reader, Morse Code Keyboard, and Morse Code Translator are available on different platforms. To your surprise, it is even supported by GBoard – the Google Keyboard.

To access Morse Code on your Gboard, open the Settings icon on the Gboard, select Languages, and tap on English (U.S.). Swipe right through the options, and then choose Morse code. Your keyboard now supports Morse Code insertion along with accessibility services, like TalkBack, Switch Access, or Select to Speak.

Source: makeuseof