Morse Code Translator in Python

Morse Code is a communication system that converts text into sequences of dots and dashes. Named after Samuel F. B. Morse, this encoding method represents each letter and number with a unique combination of short signals (dots) and long signals (dashes).

The system is widely used in telecommunications and cryptography. Each character in the English alphabet corresponds to a specific pattern of dots (.) and dashes (-).

Morse Code Dictionary

Here's the complete mapping of characters to Morse code patterns ?

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

How It Works

Encryption Process:

1. Extract each character from the input message
2. Look up the corresponding Morse code pattern
3. Add single space between each Morse code sequence
4. Add double space between words

Decryption Process:

1. Add a space at the end of the Morse code string
2. Parse each Morse sequence until a space is encountered
3. Look up the character for each Morse pattern
4. Handle double spaces as word separators

Implementation

Complete Morse Code Translator

# Dictionary representing the morse code chart
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':'-----', ',':'--..--',
    '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-',
    '(':'-.--.', ')':'-.--.-'
}

def encrypt_to_morse(message):
    """Convert text message to Morse code"""
    morse_code = ''
    for char in message.upper():
        if char != ' ':
            if char in MORSE_CODE_DICT:
                morse_code += MORSE_CODE_DICT[char] + ' '
        else:
            morse_code += ' '  # Add extra space for word separation
    return morse_code.strip()

def decrypt_from_morse(morse_message):
    """Convert Morse code back to text"""
    morse_message += ' '  # Add space at end for parsing
    decoded = ''
    current_code = ''
    
    i = 0
    while i < len(morse_message):
        if morse_message[i] != ' ':
            current_code += morse_message[i]
        else:
            # Check for double space (word separator)
            if i + 1 < len(morse_message) and morse_message[i + 1] == ' ':
                decoded += ' '
                i += 1  # Skip the second space
            elif current_code:
                # Find character for this morse code
                for char, code in MORSE_CODE_DICT.items():
                    if code == current_code:
                        decoded += char
                        break
                current_code = ''
        i += 1
    
    return decoded

# Test the functions
message = "HELLO WORLD"
print(f"Original: {message}")

# Encrypt to Morse
morse = encrypt_to_morse(message)
print(f"Morse: {morse}")

# Decrypt back to text
decoded = decrypt_from_morse(morse)
print(f"Decoded: {decoded}")
Original: HELLO WORLD
Morse: .... . .-.. .-.. ---  .-- --- .-. .-.. -..
Decoded: HELLO WORLD

Interactive Morse Code Translator

def morse_translator():
    """Interactive Morse code translator"""
    
    while True:
        print("\n=== Morse Code Translator ===")
        print("1. Text to Morse Code")
        print("2. Morse Code to Text")
        print("3. Exit")
        
        choice = input("Enter your choice (1-3): ")
        
        if choice == '1':
            text = input("Enter text to convert: ")
            morse = encrypt_to_morse(text)
            print(f"Morse Code: {morse}")
            
        elif choice == '2':
            morse = input("Enter Morse code (separate letters with spaces): ")
            text = decrypt_from_morse(morse)
            print(f"Decoded Text: {text}")
            
        elif choice == '3':
            print("Goodbye!")
            break
        else:
            print("Invalid choice! Please try again.")

# Example usage
text_input = "SOS"
morse_output = encrypt_to_morse(text_input)
print(f"'{text_input}' in Morse: {morse_output}")

morse_input = "... --- ..."
text_output = decrypt_from_morse(morse_input)
print(f"'{morse_input}' decoded: {text_output}")
'SOS' in Morse: ... --- ...
'... --- ...' decoded: SOS

Key Features

Feature Description Usage
Encryption Text to Morse code Communication, learning
Decryption Morse code to text Receiving messages
Word Separation Double spaces between words Clear message structure

Conclusion

Morse code translation in Python is straightforward using dictionary mapping. The encrypt function converts text to dots and dashes, while the decrypt function reverses the process, making it useful for communication systems and educational purposes.

Updated on: 2026-03-25T04:59:19+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements