Skip to content

Instantly share code, notes, and snippets.

@sarmadgulzar
Last active June 19, 2024 17:59
Show Gist options
  • Select an option

  • Save sarmadgulzar/4178668fbd4dfdf5a89dbed8466f3d95 to your computer and use it in GitHub Desktop.

Select an option

Save sarmadgulzar/4178668fbd4dfdf5a89dbed8466f3d95 to your computer and use it in GitHub Desktop.
Morse Code Encoder and Decoder
{"0":"-----","1":".----","2":"..---","3":"...--","4":"....-","5":".....","6":"-....","7":"--...","8":"---..","9":"----.","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":"--..",".":".-.-.-",",":"--..--","?":"..--..","'":".----.","!":"-.-.--","/":"-..-.","(":"-.--.",")":"-.--.-","&":".-...",":":"---...",";":"-.-.-.","=":"-...-","+":".-.-.","-":"-....-","_":"..--.-","\"":".-..-.","$":"...-..-","@":".--.-.","¿":"..-.-","¡":"--...-"}
import json
class MorseCodeConverter:
def __init__(self, mapping_file: str = "mapping.json") -> None:
self.morse_code_mapping: dict[str, str] = self._load_morse_code_mapping(
mapping_file
)
@staticmethod
def _load_morse_code_mapping(mapping_file: str) -> dict[str, str]:
with open(mapping_file, "r") as file:
return json.load(file)
def decode_morse_code(self, morse_code: str) -> str:
words: list[str] = morse_code.split(" ")
decoded_text: list[str] = []
for word in words:
letters: list[str] = word.split(" ")
decoded_word: str = "".join(
next(
char
for char, code in self.morse_code_mapping.items()
if code == letter
)
for letter in letters
if letter in self.morse_code_mapping.values()
)
decoded_text.append(decoded_word)
return " ".join(decoded_text)
def encode_text_to_morse(self, text: str) -> str:
morse_code: list[str] = [
self.morse_code_mapping.get(char.upper(), "") for char in text
]
return " ".join(morse_code)
if __name__ == "__main__":
converter = MorseCodeConverter()
text_to_encode = "HELLO WORLD!"
encoded_morse_code = converter.encode_text_to_morse(text_to_encode)
print("Encoded Morse code:", encoded_morse_code)
morse_code_to_decode = ".... . .-.. .-.. --- .-- --- .-. .-.. -.. -.-.--"
decoded_text = converter.decode_morse_code(morse_code_to_decode)
print("Decoded text:", decoded_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment