Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
morse_code_converter.py
#!/usr/bin/env python3
########################################################################################
#
# Version
# -------
# v1.0.3
#
# License
# -------
# MIT License
# Copyright (c) 2020-present Hunter T.
#
########################################################################################
"""
Converts morse code to English and vise versa.
Notes
-----
The script can only convert one way. If you mix morse code and English in your
phrase/string, you will be asked to renter it. This occurs because an error is produced,
and by doing this, it can easily be circumvented.
"""
####[ Variables ]#######################################################################
translation = {
"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": "----- ",
".": ".-.-.- ",
",": "--..-- ",
"?": "..--.. ",
"/": "-..-. ",
"@": ".--.-. ",
" ": " ",
}
####[ Main ]############################################################################
while True:
user_input = input("Enter your english or morse code message:\n").upper()
# Like saying, for c in user_input: if c in translation: ...
if all(c in translation for c in user_input):
morse = "".join(map(translation.get, user_input))
print(morse)
break
if all(c in ".- " for c in user_input):
# v: k for k, v reverses/makes the variables change places
trans_back = {v.rstrip(" "): k for k, v in translation.items()}
text = "".join(map(trans_back.get, user_input.split(" ")))
print(text)
break
print("Invalid input: enter a message only containing english or morse code\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment