简体   繁体   中英

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

I am working on a Morse Code translator within CodeSkulptor (Python 2), and have a function working to translate between regular text and Morse code:

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 + '  ' 

But, I can't get the Morse Code to text translation working. It only ever outputs E or T, which are a single dot or dash respectively. I believe it's because my for loop runs through individual characters, and doesn't register a sequence of dots and dashes, which match with different values in the dictionary. I'm also having difficulty for the function to add one space based on whether there is a different letter, or two spaces when there is a different word. Here's the code for the translation between Morse code and text:

    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 + ' '

Your suspicion is correct.

You need to consider spaces between Morse sequences, which means that you must not output a text character as soon as you have a Morse element, but must wait for a full code (multiple signals, and you do not know how many beforehand) to come in .

Each time you read a space (or run out of input), then you examine what you got so far:

...  ---  ...

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

...and you get "SOS"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM