给定一系列编码字母列表后,如何在单词之间插入空格?

问题描述

找出“ o”的东西。它正在使用列表中的第二个元素,而不是列表中的第二个列表。但是现在我回到间隔问题...

MORSE = {'.-':    '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','-----': '0','.----': '1','..---': '2','...--': '3','....-': '4','.....': '5','-....': '6','--...': '7','---..': '8','----.': '9'
        }

def morse_decoder(code):
    words = code.split("   ")
    words2d = []
    for i in words:
        words = i.split()
        words2d.append(words)
    array = []
    for j in range(len(words2d)):
        for k in range(len(words2d[j])):
            array.append(MORSE[words2d[j][k]])
        array.append(" ")
    string = "".join(array)
    return string.capitalize()

if __name__ == '__main__':
    print("Example:")
    print(morse_decoder('... --- ...   ...'))
    print(morse_decoder("... --- -- .   - . -..- -"))

    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert morse_decoder("... --- -- .   - . -..- -") == "Some text"
    assert morse_decoder("..--- ----- .---- ---..") == "2018"
    assert morse_decoder(".. -   .-- .- ...   .-   --. --- --- -..   -.. .- -.--") == "It was a good day"
    print("Coding complete? Click 'Check' to earn cool rewards!")

您会注意到,我的输出是输入“ ... ----..-....--”的“某些文本”,而不是“某些文本”(末尾没有空格)。看来,第一个问题的解决方案创建了一个新问题。越来越近...任何指导表示赞赏。谢谢。


因此解决了我最初获得正确间距的问题。但是经过进一步测试,我没有得到想要的结果。我说我想要“ Sos o”,这就是现在正在打印的内容。但是我真正想要的是该输入的“ Sos s”。

问题似乎出在我对word2d列表的定义中。我要完成的工作是在其自己的列表中包含每个单词的莫尔斯电码。但是出于某种原因,我真的很想理解它可以正确创建第一个单词列表,但是第二个单词是“ o”的摩尔斯电码。 Stefan在下面给了我一些替代代码来执行该功能的基本任务(将morsecode转换为英语),但是我仍然想知道我的代码出了什么问题。


我正在创建一个解码莫尔斯电码消息的函数,但在最终字符串中获得适当的间距方面遇到了困难。基本上,我希望每个单词之间都有一个空格。而且我只能设法在每个字母之间完全没有间距(如下面的代码所示)或空格,这也是不希望的。我在下面的代码中有目的地组织了words2d列表,以便每个(编码的)单词都在自己的列表中,我想我可能走在正确的轨道上,但不确定从那里去哪里。

MORSE = {'.-':    'a','----.': '9'
        }

def morse_decoder(code):
    words = code.split("   ")
    words2d = []
    for i in range(len(words)):
        words = words[i].split()
        words2d.append(words)
    array = []
    for j in range(len(words2d)):
        for k in range(len(words2d[j])):
            array.append(MORSE[words2d[j][k]])
        array.append(" ") #This is the line I was missing initially
    string = "".join(array)
    return string.capitalize()

print(morse_decoder('... --- ...   ...')) #should print "Sos s"

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)