需要帮助制作摩尔斯电码到文本翻译器 | Python

Need help making a Morse Code to Text Translator | Python

所以我在制作摩尔斯电码到文本翻译器时遇到了一些问题。然而,我将文本转为莫尔斯码,当我尝试将莫尔斯码转为文本时,它没有成功。我在网上查了一下,因为我是 python 的新手,所以我无法真正理解其中的大部分内容,所以我决定自己制作一个。只要没有空格就可以正常工作,但是当有空格时,我会收到此错误。

Text to Morse or Morse to Text
Please type ttm for text to morse or type mtt for morse to text.
mtt
What would you like to have be translated to English?
.... ..  . ...- . .-. -.-- --- -. .
hiTraceback (most recent call last):
 File "main.py", line 61, in <module>
   print(mtt_dict[words], end="")
KeyError: ''

我翻译了“大家好”,但没用

代码如下:

ttm_dict = { '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':'--..', 
                    '1':'.----', '2':'..---', '3':'...--', 
                    '4':'....-', '5':'.....', '6':'-....', 
                    '7':'--...', '8':'---..', '9':'----.', 
                    '0':'-----', ', ':'--..--', '.':'.-.-.-', 
                    '?':'..--..', '/':'-..-.', '-':'-....-', 
                    '(':'-.--.', ')':'-.--.-'}

mtt_dict = {'-.--.-':')' ,'.--.-':'('                    
 ,'-....-':'-' ,'.-..-':'/' ,'..--..':'?'                    
 ,'-.-.-.':'.' ,'--..--':' ,' ,'-----':'0'                    
 ,'.----':'9' ,'..---':'8' ,'...--':'7'                    
 ,'....-':'6' ,'.....':'5' ,'-....':'4'                    
 ,'--...':'3' ,'---..':'2' ,'----.':'1'                    
 ,'..--':'z' ,'--.-':'y' ,'-..-':'x'                    
 ,'--.':'w' ,'-...':'v' ,'-..':'u'                    
 ,'-':'t' ,'...':'s' ,'.-.':'r'                    
 ,'-.--':'q' ,'.--.':'p' ,'---':'o'                    
 ,'.-':'n' ,'--':'m' ,'..-.':'l'                    
 ,'-.-':'k' ,'---.':'j' ,'..':'i'                    
 ,'....':'h' ,'.--':'g' ,'.-..':'f'                    
 ,'.':'e' ,'..-':'d' ,'.-.-':'c'                    
 ,'...-':'b' ,'-.':'a'
}
question = input("Text to Morse or Morse to Text\nPlease type ttm for text to morse or type mtt for morse to text.\n")

#Text to Morse
if question == "ttm":
  encrypt_q = input("What would you like have be translated to Morse Code\n")
  encrypt = encrypt_q.lower()
  morse = "" 
  for letter in encrypt: 
    encrypt.lower()
    if letter != ' ': 

            morse += ttm_dict[letter] + ' '
    else: 

            morse += ' '
  print(morse) 
  #Morse to Text
elif question == "mtt":
  decrypt = input("What would you like to have be translated to English?\n")
  lenword = len(decrypt)
  words = ''
  for i in decrypt:
    if i != ' ':
        words=words+i
        if i not in mtt_dict:
            print('Data not formatted properly')
            break
    else:
        print(mtt_dict[words], end="")
        words = ''

    #If they are cannot read
else:
  print("Invalid option")

任何帮助将不胜感激

我认为是当两个 space 紧挨着彼此时。如果这应该意味着单词之间的 space 那么只需在 mtt_dict 中添加一个包含 space 字符值的空字符串键,它应该可以工作。

然后我认为你应该将检查键是否在 mtt_dict 中的代码移动到打印字符

之前的 else 部分
  for i in decrypt:
    if i != ' ':
        words += i
    else:
        if words not in mtt_dict:
            print('Data not formatted properly')
            break
        print(mtt_dict[words], end="")
        words = ''

我认为不需要 2 个单独的字典。你可以用一个字典实现转换。 PFB代码:

MORSE_CODE_DICT = { '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':'--..',
                    '1':'.----', '2':'..---', '3':'...--',
                    '4':'....-', '5':'.....', '6':'-....',
                    '7':'--...', '8':'---..', '9':'----.',
                    '0':'-----', ', ':'--..--', '.':'.-.-.-',
                    '?':'..--..', '/':'-..-.', '-':'-....-',
                    '(':'-.--.', ')':'-.--.-'
}
question = input("Text to Morse or Morse to Text\nPlease type 'ttm' for text to morse or type 'mtt' for morse to text.\n")

#Text to Morse
if question == "ttm":
    encrypt_q = input("What would you like have be translated to Morse Code\n")
    message = encrypt_q.upper()
    cipher = ''
    for letter in message:
        if letter != ' ':
            # Looks up the dictionary and adds the correspponding morse code along with a space to separate morse codes for different characters
            cipher += MORSE_CODE_DICT[letter] + ' '
        else:
            # 1 space indicates different characters and 2 indicates different words
            cipher += ' '
    print(cipher)
#Morse to Text
elif question == "mtt":
    message = input("What would you like to have be translated to English?\n")
    # extra space added at the end to access the last morse code
    message += ' '
    decipher = ''
    citext = ''
    for letter in message:
        # checks for space
        if (letter != ' '):
            # counter to keep track of space
            i = 0
            # storing morse code of a single character
            citext += letter
            # in case of space
        else:
            # if i = 1 that indicates a new character
            i += 1
            # if i = 2 that indicates a new word
            if i == 2:
                # adding space to separate words
                decipher += ' '
            else:
                # accessing the keys using their values (reverse of encryption)
                decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT.values()).index(citext)]
                citext = ''
    print(decipher)
else:
    print("Invalid option")

输出:

摩尔斯转文字:

Text to Morse or Morse to Text
Please type 'ttm' for text to morse or type 'mtt' for morse to text.
mtt
What would you like to have be translated to English?
.... ..  . ...- . .-. -.-- --- -. .
HI EVERYONE

发短信给莫尔斯:

Text to Morse or Morse to Text
Please type 'ttm' for text to morse or type 'mtt' for morse to text.
ttm
What would you like have be translated to Morse Code
HI EVERYONE
.... ..  . ...- . .-. -.-- --- -. .

您必须构建一个 encoder/decoder,@Jolbas 告诉您,您的问题是 明确地 逐字分隔。

如果合同分别是字符和单词的单双 您可以以这种方式使用拆分:

<phrase>.split('  ') for word # 2 spaces
<word>.split(' ') for characters # 1 space

命中:

所以所有这些都可以使用嵌套列表理解来完成

[ [c for c in word] for word in phrase]

使用这个技巧,大部分问题都解决了。

这是一个简洁的版本(不是所有的人都喜欢嵌套推导……反正也不错)

密码

ttm_dict = { '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':'--..', '1':'.----', '2':'..---', '3':'...--',
            '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.',
            '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-',
            '(':'-.--.', ')':'-.--.-'}

mtt_dict = {v:k for k,v in ttm_dict.items()}
question = input("Text to Morse or Morse to Text\nPlease type ttm for text to morse or type mtt for morse to text.\n")
if question == "ttm":
  encrypt_q = input("What would you like have be translated to Morse Code\n")
  # ' ' (single space, char separator
  # '  ' (double space) word separator
  morse = '  '.join([ ' '.join([ttm_dict[c] for c in word]) for word in encrypt_q.lower().split(' ')])
  print(morse)

elif question == "mtt":
  decrypt = input("What would you like to have be translated to English?\n")
  print(' '.join([''.join([mtt_dict[c] for c in word.split(' ')]) for word in decrypt.split('  ')]))

else:
  print("Invalid option")

这里是结果:

Please type ttm for text to morse or type mtt for morse to text.
ttm
What would you like have be translated to Morse Code
ciao da glauco
-.-. .. .- ---  -.. .-  --. .-.. .- ..- -.-. ---

Please type ttm for text to morse or type mtt for morse to text.
mtt
What would you like to have be translated to English?
-.-. .. .- ---  -.. .-  --. .-.. .- ..- -.-. ---
ciao da glauco