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.4
# License: MIT License
# Copyright (c) 2020-2021 Hunter T.
#
########################################################################################
"""
Convert morse code to English and vise versa.
:note: The script can only convert one way. If you mix morse code and English in your
phrase/string, you will be asked to re-enter it.
"""
####[ 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")
@StrangeRanger

This comment has been minimized.

Copy link
Owner Author

@StrangeRanger StrangeRanger commented Jun 7, 2021

Project Tracker

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment