Home Articles Categories Series
Pythonise Just now

A simple Python Morse code translator

Translating Morse code to text and back again with Python!


Article Posted on by in Python
Julian Nash · 7 months ago in Python

A simple Morse code translator class with 2 methods that will return Morse code from a string of text and return a string of text from Morse code.

The sample also includes a small suite of basic tests.

The Morse code used is just a small set of the International standard - Referenced here

Code

morse.py

class MorseCodeTranslator:

    # International morse code (sample)
    morse = {
        # Letters
        "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": "--..",
        # Numbers
        "0": "-----",
        "1": ".----",
        "2": "..---",
        "3": "...--",
        "4": "....-",
        "5": ".....",
        "6": "-....",
        "7": "--...",
        "8": "---..",
        "9": "----.",
        # Punctuation
        "&": ".-...",
        "'": ".----.",
        "@": ".--.-.",
        ")": "-.--.-",
        "(": "-.--.",
        ":": "---...",
        ",": "--..--",
        "=": "-...-",
        "!": "-.-.--",
        ".": ".-.-.-",
        "-": "-....-",
        "+": ".-.-.",
        '"': ".-..-.",
        "?": "..--..",
        "/": "-..-.",
    }

    def translate_morse(self, morse, strict=True):

        """
        Translates morse code to text using a small set of Internation Morse code.

        Accepts:
            morse (str): A string of morse code to translate
            strict (bool): If True, parse and return morse code containing 4 spaces

        Returns:
            str: A translated string of text
        """

        if morse == "":
            return "You must provide a string of text to translate"

        if "    " in morse:
            if strict:
                return "Unable to translate morse code. Found 4 spaces in morse code string"
            else:
                morse.replace("    ", "   ")

        translation = ""

        words = morse.split("   ")

        for morse_word in words:
            chars = morse_word.split(" ")
            for char in chars:
                for k, v in self.morse.items():
                    if char == v:
                        translation += k
            translation += " "

        return translation.rstrip()

    def translate_text(self, text):

        """
        Translates text to morse code using a small set of Internation Morse code.

        Accepts:
            text (str): A string of text to translate

        Returns:
            str: A string translated to Morse code
        """

        if text == "":
            return "You must provide a morse code string to translate"

        translation = ""

        words = text.split(" ")

        for word in words:
            w = list()
            for char in word:
                if char.lower() in self.morse:
                    w.append(self.morse[char.lower()])

            translation += " ".join(w)
            translation += "   "

        return translation.rstrip()

Tests

tests.py

import unittest
from morse import MorseCodeTranslator


class TestMorseCodeTranslator(unittest.TestCase):

    # Morse code to text
    def test_morse_to_text_no_morse(self):
        translator = MorseCodeTranslator()
        morse = ""
        expected_output = "You must provide a string of text to translate"
        self.assertEqual(translator.translate_morse(morse), expected_output)

    def test_morse_to_text(self):
        translator = MorseCodeTranslator()
        morse = ".... . .-.. .-.. ---   .-- --- .-. .-.. -.."
        expected_output = "hello world"
        self.assertEqual(translator.translate_morse(morse), expected_output)

    def test_morse_to_numbers(self):
        translator = MorseCodeTranslator()
        morse = ".---- ..--- ...-- ....- ..... -.... --... ---.. ----. -----"
        expected_output = "1234567890"
        self.assertEqual(translator.translate_morse(morse), expected_output)

    def test_morse_to_punctuation(self):
        translator = MorseCodeTranslator()
        morse = ".-... .----. .--.-. -.--.- -.--. ---... --..-- -...- -.-.-- .-.-.- -....- .-.-. .-..-. ..--.. -..-."
        expected_output = "&'@)(:,=!.-+\"?/"
        self.assertEqual(translator.translate_morse(morse), expected_output)

    def test_morse_to_text_not_strict(self):
        translator = MorseCodeTranslator()
        morse = ".... . .-.. .-.. ---    .-- --- .-. .-.. -.."
        expected_output = "hello world"
        self.assertEqual(
            translator.translate_morse(morse, strict=False), expected_output
        )

    def test_morse_to_text_strict(self):
        translator = MorseCodeTranslator()
        morse = ".... . .-.. .-.. ---    .-- --- .-. .-.. -.."
        expected_output = (
            "Unable to translate morse code. Found 4 spaces in morse code string"
        )
        self.assertEqual(
            translator.translate_morse(morse, strict=True), expected_output
        )

    # Text to morse code
    def test_text_to_morse_no_text(self):
        translator = MorseCodeTranslator()
        text = ""
        expected_output = "You must provide a morse code string to translate"
        self.assertEqual(translator.translate_text(text), expected_output)

    def test_text_to_morse(self):
        translator = MorseCodeTranslator()
        text = "hello world"
        expected_output = ".... . .-.. .-.. ---   .-- --- .-. .-.. -.."
        self.assertEqual(translator.translate_text(text), expected_output)

    def test_numbers_to_morse(self):
        translator = MorseCodeTranslator()
        text = "1234567890"
        expected_output = ".---- ..--- ...-- ....- ..... -.... --... ---.. ----. -----"
        self.assertEqual(translator.translate_text(text), expected_output)

    def test_punctuation_to_morse(self):
        translator = MorseCodeTranslator()
        text = "&'@)(:,=!.-+\"?/"
        expected_output = ".-... .----. .--.-. -.--.- -.--. ---... --..-- -...- -.-.-- .-.-.- -....- .-.-. .-..-. ..--.. -..-."
        self.assertEqual(translator.translate_text(text), expected_output)

    def test_all_to_morse(self):
        translator = MorseCodeTranslator()
        text = "Hello world.. 12 & 4 56 7+8 9 10, (this) is? 'Just' @ some <testing>!"
        expected_output = ".... . .-.. .-.. ---   .-- --- .-. .-.. -.. .-.-.- .-.-.-   .---- ..---   .-...   ....-   ..... -....   --... .-.-. ---..   ----.   .---- ----- --..--   -.--. - .... .. ... -.--.-   .. ... ..--..   .----. .--- ..- ... - .----.   .--.-.   ... --- -- .   - . ... - .. -. --. -.-.--"
        self.assertEqual(translator.translate_text(text), expected_output)


if __name__ == "__main__":
    unittest.main()

Example

example.py

from morse import MorseCodeTranslator

translator = MorseCodeTranslator()

text = "This string has been translated to morse code and back again"

# Translate text to morse code
morse = translator.translate_text(text)

# Translate morse code to text
translated_text = translator.translate_morse(morse)

print(morse)
print(translated_text)

Usage

Clone the repo

After cloning the repo, to run the example:

python example.py

Output:

- .... .. ...   ... - .-. .. -. --.   .... .- ...   -... . . -.   - .-. .- -. ... .-.. .- - . -..   - ---   -- --- .-. ... .   -.-. --- -.. .   .- -. -..   -... .- -.-. -.-   .- --. .- .. -.
this string has been translated to morse code and back again

Feel free to change the text in the example. The example calls translate_morse using the output of translate_text, which is provided with a string.

Testing

The repo includes a small suite of basic tests using Pythons unittest module. To run the tests:

python tests.py
Last modified · 01 Apr 2019
Did you find this article useful?
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License
Contents
Loading...