user14007967
user14007967

Reputation:

.split() and triple spaces

I am writing a small script to convert morse code into plain text.

For example:

"···· · −·−−   ·−−− ··− −·· ·" 

would return "HEYJUDE". But, I would like it to be "HEY JUDE" instead, with a space in between the two words.

There are 3 spaces in between the morse code for "HEY" and "JUDE", I don't think .split() can help me here. Could you give me a pointer?

def decodeMorse(morse_code):
    morseDict = {".-" : "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"
                 }
    cipher = morse_code.split(" ")
    plain = []
    for n in cipher:
        plain.append(morseDict[n])
    plain = "".join(plain)
    return plain

Upvotes: 0

Views: 84

Answers (3)

Saba
Saba

Reputation: 474

If your input looks like this, you can split them first by triple space and then iterate on each word separately.

code = ".... . −.−−   .−−− ..− −.. ."
words = code.split("   ")

Upvotes: 0

0x262f
0x262f

Reputation: 36

At the first line of decodeMorse(), you can replace the middle space among 3 adjacent spaces to any different char:

morse_code = morse_code.replace('   ', ' @ ')

then add this char to morseDict .

morseDict['@']=' '

The rest of your code need no modification.

Upvotes: 2

Cyril FRANCOIS
Cyril FRANCOIS

Reputation: 88

Maybe you could two steps of split, the first one would be

.split('   ') #with 3 spaces

to decode word by word and then decoding each word, adding your desired space between then!

Upvotes: 0

Related Questions