-6

这是我的代码:

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."

我如何能够打印消息,用“莫尔斯电码”切换字母表中的字母

4

2 回答 2

3

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

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

我把它留在'.'了那里,因为它没有出现在你的字典中,我不知道你想如何处理它。

于 2014-11-11T15:58:26.887 回答
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
于 2021-06-24T19:21:45.287 回答