<p>这样的方法应该有效:
基本上,当有空格时,它将字符串拆分,生成一个列表,其中每个项目都是一个摩尔斯电码字母。然后它对照字典检查每个字母,并取英文对应的字母。最后,它将所有这些放入一个列表中,再次将其转换为字符串并打印出来。
希望有帮助!在</p>
<pre><code>morse_eng_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"}
nomorse = input("Enter your Morse code here:")
nomorse_list = nomorse.split() #this splits the string up wherever there is a space
not_morse = []
morse = True #The code is morse (so far)
for letter in nomorse_list:
eng_letter = False
for key in morse_eng_dict.keys(): #for each of the morse code letters in the dictionary
if letter == key:
eng_letter = morse_eng_dict[key]
if eng_letter: #if a letter was found that corresponds
not_morse.append(eng_letter)
else:
print("Input is not valid morse code.")
morse = False
if morse == True:
string = "".join(not_morse) #joining the string together (without spaces in between)
print(string)
</code></pre>