回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>所以我在制作莫尔斯电码到文本转换器时遇到了一些麻烦。我给莫尔斯发了短信,然而,当我试着让莫尔斯发短信时,却没有成功。我在网上查了一下,因为我是python新手,所以我不能真正理解它的大部分内容,所以我决定自己制作一个。只要没有空格,它就可以工作,但当有空格时,我会得到这个错误</p>
<pre><code>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: ''
</code></pre>
<p>我翻译了“大家好”,但它并没有真正起作用</p>
<p>代码如下:</p>
<pre><code>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")
</code></pre>
<p>任何帮助都将不胜感激</p>