morse code translater - python

776 views Asked by At

Here is my code:

morse_code = {}
morse_code["A"] = "* _"
morse_code["B"] = "_ * * *"
morse_code["C"] = "_ * _ *"
morse_code["D"] = "_ * *"
morse_code["E"] = "*"
morse_code["F"] = "* * _ *"
morse_code["G"] = "_ _ *"
morse_code["H"] = "* * * *"
morse_code["I"] = "* *"
morse_code["J"] = "* _ _ _"
morse_code["K"] = "_ * _"
morse_code["L"] = "* _ * *"
morse_code["M"] = "_ _"
morse_code["N"] = "_ *"
morse_code["O"] = "_ _ _"
morse_code["P"] = "* _ _ *"
morse_code["Q"] = "_ _ * _"
morse_code["R"] = "* _ *"
morse_code["S"] = "* * *"
morse_code["T"] = "_"
morse_code["U"] = "* * _"
morse_code["V"] = "* * * _"
morse_code["W"] = "* _ _"
morse_code["X"] = "_ * * _"
morse_code["Y"] = "_ * _ _"
morse_code["Z"] = "_ _ * *"
morse_code[" "] = " | "

phrase = "BOTH FICKLE DWARVES JINX MY PIG QUIZ."

How would I be able to print the message switching out the letters of the alphabet with the "morse code"

2

There are 2 answers

0
Cory Kramer On

You could use a list comprehension to iterate over all the letters and substitute from your dictionary.

print(''.join([morse_code.get(i,i) for i in phrase]))

I left the '.' in there since it does not appear in your dictionary, I don't know how you want to handle that.

0
Deidra Mullan On

A function like this can translate the strings to morse code leveraging the data in your dictionary.

def text_to_morse_code():
    translated_text = ""
    for char in phrase:
        for k, v in morse_code.items():
            if char == k:
                translated_text += v
    return translated_text