Morse code is a method to encode a message using dots, dashes, and spaces. It’s widely used to communicate messages secretly.
You might have seen morse code usage in navy scenes of many movies to communicate messages. We are talking about the same morse code here, but the only difference is that we are going to write a Python program to translate from English to Morse code and vice versa.
About Morse code
Morse code has different patterns for each English alphabet, number, punctuation, and non-Latin characters. Once you know the morse code patterns for different characters, it will be easy to encode and decode them. You can refer Wikipedia page of morse code for more details and patterns.
In this tutorial, we will learn how to encode plain English text into morse code and vice versa. We will be using English alphabets, numbers, and punctuation while encoding the decoding. If you want to add more types of characters, you can easily do it once you learn the base of encoding and decoding.
One thing to remember is that both uppercase and lowercase alphabets have the same morse code pattern. This is because the morse code is mainly used for communication which doesn’t care about alphabet cases like everyday conversations.
Let’s get into the coding part for encoding and decoding.
English to Morse code
The algorithm to convert plain English text to morse code is straightforward. Let’s check the algorithm.
- Create a dictionary with the morse code patterns mappings with English alphabets, numbers, and punctuations.
- Iterate over the text and add the morse code pattern of each text character to the result.
- Morse code contains a space after each character and a double space after each word.
- So when we encounter space in the text, which is the separator for words, we need to add double space to the result.
- The resultant string will be the morse code that we needed.
- Finally, return the result.
Try to write the code in Python. Don’t worry, even if you are not able to write it completely.
Let’s check the code for encoding plain English text into morse code.
# dictionary for mapping characters to morse code
CHARS_TO_MORSE_CODE_MAPPING = {
'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': '-----',
'.': '.-.-.-',
',': '--..--',
'?': '..--..',
'\'': '· − − − − ·',
'!': '− · − · − −',
'/': '− · · − ·',
'(': '− · − − ·',
')': '− · − − · −',
'&': '· − · · ·',
':': '− − − · · ·',
';': '− · − · − ·',
'=': '− · · · −',
'+': '· − · − ·',
'-': '− · · · · −',
'_': '· · − − · −',
'"': '· − · · − ·',
'$': '· · · − · · −',
'@': '· − − · − ·',
}
# function to encode plain English text to morse code
def to_morse_code(english_plain_text):
morse_code = ''
for char in english_plain_text:
# checking for space
# to add single space after every character and double space after every word
if char == ' ':
morse_code += ' '
else:
# adding encoded morse code to the result
morse_code += CHARS_TO_MORSE_CODE_MAPPING[char.upper()] + ' '
return morse_code
morse_code = to_morse_code(
'Geekflare produces high-quality technology & finance articles, makes tools, and APIs to help businesses and people grow.'
)
print(morse_code)
You can see the morse code output below. You should also see a similar morse code in your terminal if you didn’t change the message.
--. . . -.- ..-. .-.. .- .-. . .--. .-. --- -.. ..- -.-. . ... .... .. --. .... − · · · · − --.- ..- .- .-.. .. - -.-- - . -.-. .... -. --- .-.. --- --. -.-- · − · · · ..-. .. -. .- -. -.-. . .- .-. - .. -.-. .-.. . ... --..-- -- .- -.- . ... - --- --- .-.. ... --..-- .- -. -.. .- .--. .. ... - --- .... . .-.. .--. -... ..- ... .. -. . ... ... . ... .- -. -.. .--. . --- .--. .-.. . --. .-. --- .-- .-.-.-
Hurray! we got the morse code. You know what comes after.
Before jumping into the decoding program, let’s stop for a while and think about how to write code to decode it.
…
You should have thought about reversing the CHARS_TO_MORSE_CODE_MAPPING
dictionary as one of the steps. Doing it manually is hectic and needs to update whenever the original mapping is changed. Let’s write code to reverse the dictionary.
def reverse_mapping(mapping):
reversed = {}
for key, value in mapping.items():
reversed[value] = key
return reversed
We are just reversing the key-value pairs of the given dictionary with the above code. The resultant dictionary will contain values are new keys and keys as new values.
We have all the pieces to decode the morse code into plain English text. Without further ado, let’s decode the morse code.
Morse code to English
We can reverse the process of morse code encoding to get the decoding algorithm. Let’s see the algorithm for decoding the morse code into plain English text.
- Reverse the
CHARS_TO_MORSE_CODE_MAPPING
dictionary using the util function we have written. - Iterate over the morse code and keep track of the current morse code character.
- If we encounter a space, it means we have a complete morse code character to decode.
- If the current morse code character is empty and we have two consecutive spaces, then add a word separator which is a single space in plain English text.
- If the above condition is false, then get the decoded character from the dictionary and add it to the result. Reset the current morse code character.
- If we didn’t encounter space, add it to the current morse character.
- If we encounter a space, it means we have a complete morse code character to decode.
- If there is the last character, add it to the result after decoding using the dictionary.
- Return the result at the end.
Let’s check the code for the above algorithm.
def reverse_mapping(mapping):
# add function code from the previous snippet...
CHARS_TO_MORSE_CODE_MAPPING = {} # add dictionary values
MORSE_CODE_TO_CHARS_MAPPING = reverse_mapping(CHARS_TO_MORSE_CODE_MAPPING)
def to_english_plain_text(morse_code):
english_plain_text = ''
current_char_morse_code = ''
i = 0
while i < len(morse_code) - 1:
# checking for each character
if morse_code[i] == ' ':
# checking for word
if len(current_char_morse_code) == 0 and morse_code[i + 1] == ' ':
english_plain_text += ' '
i += 1
else:
# adding decoded character to the result
english_plain_text += MORSE_CODE_TO_CHARS_MAPPING[
current_char_morse_code]
current_char_morse_code = ''
else:
# adding morse code char to the current character
current_char_morse_code += morse_code[i]
i += 1
# adding last character to the result
if len(current_char_morse_code) > 0:
english_plain_text += MORSE_CODE_TO_CHARS_MAPPING[
current_char_morse_code]
return english_plain_text
english_plain_text = to_english_plain_text(
'--. . . -.- ..-. .-.. .- .-. . .--. .-. --- -.. ..- -.-. . ... .... .. --. .... − · · · · − --.- ..- .- .-.. .. - -.-- - . -.-. .... -. --- .-.. --- --. -.-- · − · · · ..-. .. -. .- -. -.-. . .- .-. - .. -.-. .-.. . ... --..-- -- .- -.- . ... - --- --- .-.. ... --..-- .- -. -.. .- .--. .. ... - --- .... . .-.. .--. -... ..- ... .. -. . ... ... . ... .- -. -.. .--. . --- .--. .-.. . --. .-. --- .-- .-.-.- '
)
print(english_plain_text)
I have given the morse code that is generated from the encoding function. We will get the following output if we run the above program.
GEEKFLARE PRODUCES HIGH-QUALITY TECHNOLOGY & FINANCE ARTICLES, MAKES TOOLS, AND APIS TO HELP BUSINESSES AND PEOPLE GROW.
Note: the output is in the English uppercase alphabet because we have used the uppercase alphabet for mapping in the dictionary.
Final Words
We have seen that the output of the decoding function is in uppercase. You can improve the program by making the output as it is in the given time by tracking the lower and upper cases of the English alphabet. This is not related to morse code, as both upper and lower cases have the same pattern. Try it, as it’s more fun to code.
That’s it for this tutorial. Use the programs we have written when you encounter morse code next time.
Happy Coding 👨💻
You may now look at how to create a random password in Python.
Also, check these English to Morse code translators.