difficulty to correct morse-english text

Question:

in converted version from morse to english – there must be one space between letters and two spaces between words. if the symbol is not possible to be converted into english (not in morse) there can be "#"

this version does not work.. ((( 
sign_eng = {'.-': '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'
                  }

text = input("Enter your Morse code here: ")
text_words = text.split('   ')
words = ''
for text_word in text_words:
    text_letters = text_word.split('  ')
    letters = ''
for text_letter in text_letters:
    if text_letter in sign_eng:
        text = words + str(sign_eng[text_letter])
    if text_letter not in sign_eng:
        text = words + "#"

    result = "".join(words)
    print(result)`

Asked By: John_

||

Answers:

words = words + str(sign_eng[text_letter])

Answered By: Pete

There are some issues with the code. Comments mark changes made:

text = input("Enter your Morse code here: ")
text_words = text.split('  ')  # 2 spaces, not 3
words = []  # a list instead of ''
for text_word in text_words:
    text_letters = text_word.split(' ')  # 1 space, not 2
    letters = ''
    for text_letter in text_letters:  # nest loop to process  all `text_words`s
        if text_letter in sign_eng:   
            text = str(sign_eng[text_letter])
        if text_letter not in sign_eng:
            text = "#"
        letters += text  # update letters
        
    words.append(letters)  # update words list
    
result = " ".join(words)  # join words with a space
print(result)
Enter your Morse code here: .... . .-.. .-.. ---  .-- --- .-. .-.. -..
hello world

Here is a more concise version:

text = input("Enter your Morse code here: ")
text_words = text.split('  ')
words = []
for text_word in text_words:
    word = "".join(sign_eng.get(letter, "#")
                   for letter in text_word.split(' '))
    words.append(word)
result = " ".join(words)
print(result)

and there’s still room for improvement

Answered By: Tim
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.