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

问题描述 投票:0回答:1

我正在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循环在单个字符中运行,而没有记录点和破折号的序列,而这些点和破折号在字典中与不同的值相匹配。我也很难让函数根据是否有不同的字母添加一个空格,或者当有不同的单词时添加两个空格。下面是摩斯码和文本之间的翻译代码。

    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 + ' '
python dictionary for-loop translation morse-code
1个回答
0
投票

你的怀疑是正确的。

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

每次 你读取了一个空格(或用完了输入),然后你检查你目前得到的东西。

...  ---  ...

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"

© www.soinside.com 2019 - 2024. All rights reserved.