<p>我认为不需要2个速率dict。您可以通过一个dict.PFB代码实现转换:</p>
<pre><code>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")
</code></pre>
<p>输出:</p>
<p>摩尔斯电文:</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?
.... .. . ...- . .-. -. - -. .
HI EVERYONE
</code></pre>
<p>摩尔斯电文:</p>
<pre><code>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
.... .. . ...- . .-. -. - -. .
</code></pre>