我如何让我的 Python 摩尔斯电码翻译器区分单个点和破折号以及它们的序列?

How would I make my Python Morse code translator distinguish between singular dots and dashes and a sequence of them?

我正在 CodeSkulptor (Python 2) 中开发摩尔斯电码翻译器,并且有一个功能可以在普通文本和摩尔斯电码之间进行转换:

def input_handler(input_text):
    global inpu
    global input_message
    global output_message

    if inpu == "Text":
        input_message = input_text
        output_message = ''
        for character in input_text.lower():
            if character != ' ':
                output_message = output_message + morse_dict[character] + ' '
            else:
                output_message = output_message + '  ' 

但是,我无法将摩尔斯电码翻译成文本。它只输出 E 或 T,分别是一个点或破折号。我相信这是因为我的 for 循环遍历了单个字符,并且没有注册一系列点和破折号,这些点和破折号与字典中的不同值相匹配。我也很难让函数根据是否有不同的字母添加一个 space,或者当有不同的单词时添加两个 space。这是摩尔斯电码和文本之间的转换代码:

    elif inpu == "Morse Code":
        input_message = input_text
        output_message = ''
        for character in input_text:
            if character != ' ':
                output_message = output_message + alpha_dict[character] + ' '
            elif character == '  ':
                output_message = output_message + ' '

你的猜测是正确的。

你需要考虑摩尔斯序列之间的spaces,这意味着你不能一有摩尔斯元素就输出一个文本字符,而是必须等待一个完整的代码(多个信号,你事先不知道有多少)进来.

每次你读到一个space(或运行输入),然后你检查你到目前为止得到了什么:

...  ---  ...

read ".", put it in buffer which is then "."
read ".", put it in buffer which is then ".."
read ".", put it in buffer which is then "..."
read " ", so check buffer; it is "...", so a "S". Empty the buffer.
read " ", so check buffer; it is empty, so do nothing
read "-", put it in buffer which is then "-"
...
nothing more to read, so check buffer; it is "...", so a "S".

...你得到 "S O S"