Morse Code to English Python
我正在制作一个程序,在那里莫尔斯电码被解密成英文。但是,当程序运行时,我把莫尔斯电码输入(例如*—这会导致程序打印出"A",程序只会给出一个空白空间。
1 2 3 4 5 6 7 8 9 | message = input("Please type a message to encrypt.") new_message ="" letters = {"*-":"A", "-***":"B", "-*-*":"C"} for let in message: if let in letters: new_message += letters[let] print(new_message) |
我正在寻找一种方法来解决这个问题,使用上面的替换方法。谢谢您。
试着用这个方法从英语到莫尔斯,反之亦然。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | def english_to_morse(message): letters = {'A': '*-', 'B': '-***', 'C': '-*-*'} return ''.join([letters[letter]+'|' for letter in message if letter in letters]) def morse_to_english(message): letters = {'A': '*-', 'B': '-***', 'C': '-*-*'} letters = {v: k for k, v in letters.items()} message = message.split('|')[0:-1] return ''.join([letters[letter] for letter in message if letter in letters]) message = input("Please type a message to encrypt.") print(english_to_morse(message)) message = input("Please type a morse code message to decrypt. Separate codes by '|'") print(morse_to_english(message)) |
我想您的输入应该是这样的
1 2 3 4 | #split every letter into list of letters message = input('Please type a message to encrypt: ').split('/') #join the list after decrypt it print("".join([letters[letter] for letter in message])) |
以下是一个解决方案:
1 2 3 4 5 6 7 8 9 10 11 | message = input("Please type a message to encrypt:") new_message ="" letters = {".-":"A", "-...":"B", "-.-.":"C",} if letters[message]: new_message = letters[message] else: new_message ="This cannot be turned to morse code" print(new_message) |
输入