- Simple Morse Code Decoder in Python
- Morse Code Representation in Python
- Building the Morse Code Decoder
- Saved searches
- Use saved searches to filter your results more quickly
- Py-geeks/Morse-Code
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- How to Create a Morse Code Translator using Python
- About Morse code
- English to Morse code
- Morse code to English
- Final Words
Simple Morse Code Decoder in Python
Morse code is a method used in telecommunication where each alphabet, number and punctuation is represented by a series of dots/dashes/spaces. It was first invented by Samuel Morse in 1930s and it has been heavily used in the navy industry. This article will describe the process to build a simple Morse Code decoder in Python.
Morse Code Representation in Python
As seen in the image above, each alphabet and number is represented by a series of dots and dashes. We can represent them as such in Python, but for better clarity, let’s translate them to ‘0’ and ‘1’ instead, where ‘0’ represents a dot, and ‘1’ represents a dash.
character = ['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','0','1','2','3','4','5','6','7','8','9']code = ['01','1000','1010','100','0','0010','110','0000','00','0111','101','0100','11','10','111','0110','1101','010','000','1','001','0001','011','1001','1011','1100','11111','01111','00111','00011','00001','00000','10000','11000','11100','11110']
As each character (i.e. an alphabet or number) corresponds to a series of 0s and 1s, we will use a dictionary structure to store them in Python. You can refer to my previous post on building a dictionary data structure in Python here.
# Define an empty dictionary 'morse_dict'
morse_dict = <># Convert the 2 lists into a dictionary using a tuple
zipped_char_code = zip(character, code)
morse_dict = dict(zipped_char_code)# Print the dictionary 'morse_dict' on the terminal line by line
for key, value in morse_dict.items():
print(key, value)
Building the Morse Code Decoder
The way the Morse Decoder will be built is that we will prompt the user to key in the Morse Code representation (i.e. in 0s and 1s), with each alphabet or number separated by a *. Once the user pressed ‘enter’, the program will decode the Morse Code and displays it in alphanumeric form.
# reverse the previous dict as it's easier to access the keys
zipped_code_char = zip(code,character)
rev_morse_dict = dict(list(zipped_code_char))
# initiating a while loop
while True:
# empty…
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Morse encoder and decoder system in python
Py-geeks/Morse-Code
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Morse encoder and decoder system in python. It is an intermediate level project but quite easy to un derstand.
This is an intermediate level project but still doesn’t need any extra libraries.
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':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-. -', '(':'-.--.', ')':'-.--.-'>
Declaring the morse code dictionary containing morse codes for alphabets and symbols.
def encrypt(message): cipher = '' for letter in message: if letter != ' ': # Looks up the dictionary and adds the # correspponding morse code # along with a space to separate # morse codes for different characters cipher += MORSE_CODE_DICT[letter] + ' ' else: # 1 space indicates different characters # and 2 indicates different words cipher += ' ' return cipher
This function takes the code in english and returns the morse encrypted message.
def decrypt(message): # extra space added at the end to access the # last morse code message += ' ' decipher = '' citext = '' for letter in message: # checks for space if (letter != ' '): # counter to keep track of space i = 0 # storing morse code of a single character citext += letter # in case of space else: # if i = 1 that indicates a new character i += 1 # if i = 2 that indicates a new word if i == 2 : # adding space to separate words decipher += ' ' else: # accessing the keys using their values (reverse of encryption) decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT .values()).index(citext)] citext = '' return decipher
This function takes the code in morse encrypted message and returns the decrypted message in english.
def main(): print("Enter 1. Encode or 2. Decode: ") choice = int(input()) if choice == 1: print("Enter the message in English to encrypt: ") message = input() result = encrypt(message.upper()) print (result) elif choice == 2: print("Enter the morse encrypted code: ") message = input() result = decrypt(message) print (result) else: print("Invalid choice") exit # Executes the main function if __name__ == '__main__': main()
Hard-coded driver function to run the program.
How to Create a Morse Code Translator using Python
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.
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.