Python Morse Code

In this article we will learn how to use Python programming to convert messages from English to Morse Code and vice versa. We will also learn how to play the Morse Code version aloud using pygame and audio files containing sound samples.

Morse Code was invented by Samuel Morse as a way to communicate messages over great distances when the only technology available worked by sending electrical pulses to other machines. You could not use voice or text, so a new way of getting messages across was needed.

The Code consists of short and long pulses, often called dots and dashes, and combinations of these represent various letters, numbers and symbols, which in turn can be combined into words to form complete messages.

Python Morse Code Converter Program Listing

The Python program below defines a dictionary ENGLISH_TO_MORSE which contains the mappings between letters and numbers, and the sequences of dots and dashes which represent them in Morse Code. The inverse, MORSE_TO_ENGLISH is then created programmatically.

We then define two functions to perform the actual conversions, both of which use what I call the accumulator pattern, where you start with an empty container (a list, here) and modify it as you loop through some collection (the characters in the message in this case).

ENGLISH_TO_MORSE = {'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': '----.'}

# Generate MORSE_TO_ENGLISH from ENGLISH_TO_MORSE
MORSE_TO_ENGLISH = {}
for key, value in ENGLISH_TO_MORSE.items():
    MORSE_TO_ENGLISH[value] = key


def english_to_morse(message):
    morse = []  # Will contain Morse versions of letters
    for char in message:
        if char in ENGLISH_TO_MORSE:
            morse.append(ENGLISH_TO_MORSE[char])
    return " ".join(morse)


def morse_to_english(message):
    message = message.split(" ")
    english = []  # Will contain English versions of letters
    for code in message:
        if code in MORSE_TO_ENGLISH:
            english.append(MORSE_TO_ENGLISH[code])
    return " ".join(english)


def main():
    while True:
        response = input("Convert Morse to English (1) or English to Morse (2)? ").upper()
        if response == "1" or response == "2":
            break

    if response == "1":
        print("Enter Morse code (with a space after each code): ")
        morse = input("> ")
        english = morse_to_english(morse)
        print("### English version ###")
        print(english)

    elif response == "2":
        print("Enter English text: ")
        english = input("> ").upper()
        morse = english_to_morse(english)
        print("### Morse Code version ###")
        print(morse)


if __name__ == "__main__":
    main()

Sample output:

Convert Morse to English (1) or English to Morse (2)? 1
Enter Morse code (with a space after each code): 
> ... --- ...
### English version ###
S O S

Sample output:

Convert Morse to English (1) or English to Morse (2)? 2
Enter English text: 
> SOS
### Morse Code version ###
... --- ...

Python English to Morse Code Audio Converter

We can make things more fun by adding actual sounds to play the Morse Code version of a message. The sound files used are from wikimedia and will need to be downloaded and placed in an appropriate folder relative to your Python program. I have provided a .zip folder containing them. Don’t forget to unzip them into the correct location…

Morse Code Audio Files

morse_code_audio

I have set PATH = "morse_code_audio/" but you can name it what you like.

The program makes use of pygame because of its handy audio capabilities. You will need to install pygame using pip if you have not already.

import pygame
import time

ENGLISH_TO_MORSE = {'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': '----.'}

TIME_BETWEEN = 0.5  # Time between sounds
PATH = "morse_code_audio/"


def verify(string):
    keys = list(ENGLISH_TO_MORSE.keys())
    for char in string:
        if char not in keys and char != " ":
            print(f"The character {char} cannot be translated.")
            raise SystemExit


def main():
    print("### English to Morse Code Audio Converter ###")
    print("Enter your message in English: ")
    message = input("> ").upper()
    verify(message)

    pygame.init()

    for char in message:
        if char == " ":
            print(" " * 3, end=" ")  # Separate words clearly
            time.sleep(7 * TIME_BETWEEN)
        else:
            print(ENGLISH_TO_MORSE[char.upper()], end=" ")
            pygame.mixer.music.load(PATH + char + '_morse_code.ogg')  # You will need these sound files
            pygame.mixer.music.set_volume(0.1)
            pygame.mixer.music.play()
            time.sleep(3 * TIME_BETWEEN)


if __name__ == "__main__":
    main()

This article has shown you how to use Python to convert messages between English and Morse Code, and also how to play Morse Code messages from sound files using Pygame. I hope you found it interesting and helpful. Happy computing!

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Join our mailing list

Join our mailing list to receive awesome articles about learning Python and Computer Science in a fun and accessible way, straight to your inbox.