试着把莫尔斯电码翻译成英语

2024-04-29 01:00:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用我用过的词典把莫尔斯电码译成英语。我试图有一个用户输入一个信息,它将他/她的信息打印成莫尔斯电码。在

我发现翻译成莫尔斯电码很容易,但是莫尔斯电码翻译成英语给我带来了一些问题。在

首先,如果我输入'.-'作为'A',我实际上得到了'E',因为它读取第一个'.'键并将其转换为'E',而不是获取整个字符串。在

这就是我目前为止所做的:)

#If user types 'N' or 'n' it proceeds this loop
if morse_message == 'N' or morse_message == 'n':    #Loops looks to see if morse_message was 'N' or 'n'
    nomorse = input("Enter your Morse code here:")
    nomorse_list = (nomorse.join('')
    for letter in nomorse_list:
        not_morse = (morse_eng_dict[letter.upper()])
        print(not_morse)

这是我的字典

^{pr2}$

我想让Python把我的莫尔斯电码打印回英语。比如说。-.. .-.. ---(你好)

这是一个项目,所以我不能使用任何花哨的模块或任何东西。 有什么想法或意见吗?谢谢您!在


Tags: or字符串用户信息messagemorse电码if
2条回答

这样的方法应该有效: 基本上,当有空格时,它将字符串拆分,生成一个列表,其中每个项目都是一个摩尔斯电码字母。然后它对照字典检查每个字母,并取英文对应的字母。最后,它将所有这些放入一个列表中,再次将其转换为字符串并打印出来。 希望有帮助!在

morse_eng_dict = {".-": "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"}

nomorse = input("Enter your Morse code here:")
nomorse_list = nomorse.split() #this splits the string up wherever there is a space
not_morse = []
morse = True    #The code is morse (so far)
for letter in nomorse_list:
    eng_letter = False
    for key in morse_eng_dict.keys():   #for each of the morse code letters in the dictionary
        if letter == key:
            eng_letter = morse_eng_dict[key]
    if eng_letter: #if a letter was found that corresponds
        not_morse.append(eng_letter)
    else:
        print("Input is not valid morse code.")
        morse = False
if morse == True:
    string = "".join(not_morse) #joining the string together (without spaces in between)
    print(string)

莫尔斯电码是有歧义的。正如你所指出的。-可以被视为e t,或a。如果不借助大词典或模糊逻辑,就没有办法轻易区分它们。在

运算符倾向于使用空格分隔字母和单词,但是: https://en.wikipedia.org/wiki/Morse_code

“一个单词的字母之间用一个等于三个点(一个破折号)的空格隔开,单词之间用一个等于七个点的空格隔开。”如果你在莫尔斯电码串中插入空格,例如:字母之间插入1个空格,单词之间插入2个空格,那么解码就轻而易举了(先拆分后映射)

相关问题 更多 >