morse code to english python3

我与影子孤独终老i 提交于 2019-11-30 07:25:59

Once you define the mapping in one direction, you can use a dict comprehension to map it the other way

CODE = {'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': '----.' 
        }

CODE_REVERSED = {value:key for key,value in CODE.items()}

Then you can use join with a generator expression to perform the translations.

def to_morse(s):
    return ' '.join(CODE.get(i.upper()) for i in s)

def from_morse(s):
    return ''.join(CODE_REVERSED.get(i) for i in s.split())

>>> to_morse('hello')
'.... . .-.. .-.. ---'
>>> from_morse('.... . .-.. .-.. ---')
'HELLO'
 mor = {'.-': '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'}
print('''Enter your msg in Morse.
Notic that: 
    1- Use / to separate the letters and space to separate words.
    2- Your message must contain only letters and numbers.
    3- '?' in output means that your input was unknowed.
    >>> ''', end = '')
msg = input(' ')              
out = []
letter = []
j = -1
for i in msg.split(' '):
    j += 1
    letter += [i.split('/')]
    for k in range(len(letter[j])):
        out += mor.get(letter[j][k], '?')
    out += ' '
print('\n      >>> Your msg is: ', end = '')
print(''.join(out))`

output:

Enter your msg in Morse.

Notic that: 

      1- Use / to separate the letters and space to separate words.
      2- Your message must contain only letters and numbers.
      3- '?' in output means that your input was unknowed.
      >>> ...././.-../.-.. .--/---/.-./.-../-.. (for example)

      >>> Your msg is: HELLO WORLD
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!