py4u blog

Morse Code Translator in Python

Morse code is a method used in telecommunication to encode text characters as sequences of two different signal durations, called dots and dashes. In this blog, we'll explore how to create a Morse code translator using Python. This can be a fun project and also has practical applications in scenarios where simple encoding/decoding is needed, like in some basic communication systems or for educational purposes.

2026-10

Table of Contents#

  1. Prerequisites
  2. Morse Code Dictionary
  3. Encoding (Text to Morse Code)
  4. Decoding (Morse Code to Text)
  5. Best Practices
  6. Example Usage
  7. Error Handling
  8. References

Prerequisites#

To follow along with this tutorial, you should have a basic understanding of Python programming. You'll need Python installed on your system (Python 3.x is recommended). No additional external libraries are required for the core functionality, as we'll be using built-in Python features like dictionaries and string manipulation.

Morse Code Dictionary#

First, we need to define a dictionary that maps each character (including letters, numbers, and some common symbols) to its corresponding Morse code representation. Here's a partial example of such a dictionary:

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': '--..',
    '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-',
    '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.',
    '.': '.-.-.-', ',': '--..--', '?': '..--..', "'": '.----.',
    '!': '-.-.--', '/': '-..-.', '(': '-.--.', ')': '-.--.-',
    '&': '.-...', ':': '---...', ';': '-.-.-.', '=': '-...-',
    '+': '.-.-.', '-': '-....-', '_': '..--.-', '"': '.-..-.',
    '$': '...-..-', '@': '.--.-.',
    ' ': '/'  # Using '/' to represent a space between words
}

Encoding (Text to Morse Code)#

The encoding function will take a text string as input and convert each character to its Morse code equivalent. Here's the Python function to do that:

def text_to_morse(text):
    morse_code = []
    text = text.upper()  # Convert input text to uppercase to match dictionary keys
    for char in text:
        if char in morse_code_dict:
            morse_code.append(morse_code_dict[char])
        else:
            # You can handle unknown characters gracefully, for example, skip them or add a placeholder
            print(f"Warning: Character {char} not found in Morse code dictionary. Skipping.")
    return " ".join(morse_code)

Common Practice:

  • Always convert the input text to a consistent case (like uppercase here) to match the dictionary keys easily.
  • Handle unknown characters appropriately. In the above code, we print a warning and skip them. You could also choose to raise an error or replace them with a default value depending on your application's requirements.

Decoding (Morse Code to Text)#

To decode Morse code back to text, we need to reverse the mapping. We'll create a new dictionary that maps Morse code sequences to characters.

reverse_morse_dict = {v: k for k, v in morse_code_dict.items()}
 
def morse_to_text(morse):
    text = []
    morse_tokens = morse.split(' ')
    for token in morse_tokens:
        if token in reverse_morse_dict:
            text.append(reverse_morse_dict[token])
        else:
            print(f"Warning: Morse code token {token} not recognized. Skipping.")
    return "".join(text)

Best Practice:

  • Precompute the reverse dictionary (as we did with reverse_morse_dict) for better performance when decoding multiple Morse code strings. This way, you don't have to recreate the reverse mapping every time you call the decoding function.

Example Usage#

Encoding Example#

input_text = "HELLO WORLD"
encoded_morse = text_to_morse(input_text)
print(encoded_morse)

Output:

.... . .-.. .-.. --- /.-- --- .-. .-.. -..

Decoding Example#

input_morse = ".... . .-.. .-.. --- /.-- --- .-. .-.. -.."
decoded_text = morse_to_text(input_morse)
print(decoded_text)

Output:

HELLO WORLD

Notice that in the decoding example, we had an extra space at the end of the Morse code input. The code still worked because we split on spaces, but in a more robust implementation, you might want to trim leading/trailing spaces.

Error Handling#

As shown in the encoding and decoding functions, we added basic error handling for unknown characters/tokens. In a real-world application, you could expand this. For example:

  • In the encoding function, if you want to be strict, you could raise a ValueError for unknown characters instead of just printing a warning.
  • In the decoding function, you could have a more detailed error message that includes the position of the unknown token in the input Morse code string.

References#

  • Morse Code Wikipedia Page - For a detailed understanding of Morse code history and standard representations.
  • Python Documentation on Dictionaries - To learn more about dictionary operations used in this implementation.

This Morse code translator in Python is a simple yet useful project that showcases basic string manipulation and dictionary usage in Python. You can further enhance it by adding features like input validation, better error handling, or integrating it with other systems (e.g., a GUI for easier interaction).