摩尔斯电码翻译 - 蟒蛇

时间:2014-11-11 15:56:08

标签: python morse-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."

我怎样才能打印出用“莫尔斯电码”切换字母表字母的信息

2 个答案:

答案 0 :(得分:3)

您可以使用列表推导来迭代所有字母并从您的字典中替换。

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

我将'.'留在那里,因为它没有出现在你的字典中,我不知道你想怎么处理它。

答案 1 :(得分:0)

这样的函数可以利用字典中的数据将字符串转换为莫尔斯电码。

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