Skip to content

Added morse code translator #655

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions morse_code_translator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Morse code translator

A very simple script to translate morse code to plain text and vice versa.

## Usage

- Copy the contents of the folder into your desired location
- Execute the script `python morse-code-translator.py`
- No packages to install.


## Authors

- [@SwarajBaral](https://www.github.com/SwarajBaral)
56 changes: 56 additions & 0 deletions morse_code_translator/morse-code-translator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import os

# Plain text to morse code 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': '--..',
'1': '.----', '2': '..---', '3': '...--',
'4': '....-', '5': '.....', '6': '-....',
'7': '--...', '8': '---..', '9': '----.',
'0': '-----', ',': '--..--', '.': '.-.-.-',
'?': '..--..', '/': '-..-.', '-': '-....-',
'(': '-.--.', ')': '-.--.-', ' ': '/'}

# Morse code to plain text dictionary.
REV_MORSE_CODE_DICT = {v: k for k, v in MORSE_CODE_DICT.items()}


def translate(text):
if not all(t == '.' or t == '-' or t == '/' or t.isspace() for t in text):
print()
print("The morse code encryption of the text is :-")
print()
return ' '.join([MORSE_CODE_DICT.get(t, '?') for t in text])
else:
print()
print("The translated text is :-")
print()
return ''.join([REV_MORSE_CODE_DICT.get(t, '?')
for t in text.split()])


if __name__ == "__main__":
os.system('cls')
print("-" * 50)
print("ENTER MORSE CODE SENTENCE TO DECODE AND NORMAL SENTENCE TO ENCODE")
print("-" * 50)
quit = False

while not quit:
print()
user_input = input("Enter a sentence: ")
print(translate(user_input.upper()))
print()
q = input(
"Do you want another translation ? (Y/Yes) or (N/No): "
).lower()
if q == 'n' or q == 'no':
quit = True

# Script by Swaraj Baral (github.com/SwarajBaral)