-1

(thanks to CoryKramer's code to the query on the post: morse code to english python3)

I am writing a morse code program. It works for string-to-morse. When making morse-to-string, it translates the morse properly but it ignores the whitespace, which I need for my output.

Here is my code:

def coder(text, to_morse=True):
    morse_key = {'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': '----.', ' ': ' '
            }

    key_reversed = {value: key for key, value in morse_key.items()}
    if to_morse:
        return ' '.join(morse_key.get(i.upper()) for i in text)
    else:
        x = ''.join([key_reversed.get(i) for i in text.split() for i in (i, ' ')][:-1])
        return str(x)

If for example, I do:

coder('-.. .- - .-   ... -.-. .. . -. -.-. .', False)

it outputs:

'D A T A S C I E N C E'

However, the output that I want is:

'DATA SCIENCE'

How should I implement the split() function whilst including whitespace?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
pancakes
  • 159
  • 1
  • 2
  • 14
  • 1
    Having space as a delimiter and also as a letter of the alphabet makes this a (little) bit harder to handle – user8408080 Mar 22 '20 at 16:54
  • 1
    Duplicate of [Python: How can I include the delimiter(s) in a string split?](https://stackoverflow.com/questions/21208223/python-how-can-i-include-the-delimiters-in-a-string-split) – Jongware Mar 22 '20 at 17:07

2 Answers2

2

Change the part under else to:

text = text.replace(' ', ',').replace(',,,', ', ,')
return ''.join(key_reversed.get(i) for i in text.split(','))
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Błotosmętek
  • 12,717
  • 19
  • 29
0

Use this in your else block

else:
    words = text.split('   ') # split on 3 spaces
    x =[]
    for word in words:
        x.append(''.join([key_reversed.get(i) for i in word.split()]))
    return ' '.join(x)
Chayan Bansal
  • 1,857
  • 1
  • 13
  • 23