Introduction
Morse code is a method of encoding text characters into sequences of dots and dashes, used historically for long-distance communication. This program enables users to convert text to Morse code and vice versa, providing a simple and interactive way to learn and work with Morse code.
Objective
The goal of this program is to create a Python-based text-to-Morse code translator and vice versa, allowing users to encode and decode text interactively.
Python Code
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 text_to_morse(text): return ' '.join(morse_code_dict[char.upper()] for char in text if char.upper() in morse_code_dict) def morse_to_text(morse): reverse_dict = {v: k for k, v in morse_code_dict.items()} return ''.join(reverse_dict[code] for code in morse.split(' ') if code in reverse_dict) def main(): print("Welcome to the Text-Morse Code Translator!") while True: print("\nOptions:") print("1. Text to Morse Code") print("2. Morse Code to Text") print("3. Exit") choice = input("Choose an option: ") if choice == '1': text = input("Enter text to convert to Morse Code: ") print("Morse Code:", text_to_morse(text)) elif choice == '2': morse = input("Enter Morse Code to convert to text (separate codes with spaces): ") print("Text:", morse_to_text(morse)) elif choice == '3': print("Goodbye!") break else: print("Invalid choice, please try again.") if __name__ == "__main__": main()
Program Explanation
This Python program translates text to Morse code and vice versa. Here’s a breakdown of the program structure:
morse_code_dict
: A dictionary mapping characters to their Morse code equivalents.text_to_morse
: Converts text into Morse code using the dictionary.morse_to_text
: Converts Morse code back to text using a reversed dictionary.main
: Provides an interactive menu for users to choose between encoding, decoding, and exiting the program.
Steps to Run the Program
- Ensure Python is installed on your system.
- Copy the code into a file named
morse_code_translator.py
. - Open a terminal or command prompt and navigate to the directory containing the file.
- Run the script using the command:
python morse_code_translator.py
. - Follow the prompts to translate text to Morse code or Morse code to text.