我在完成这段代码时遇到了问题。我最初的计划是接受一个长字符串作为输入,例如 '... ---.. -. - .. .. .-. .--'然后能够使用 morse_code = [code_input.split(' ')] 将它们分开并单独运行它们但是我要么从索引返回第一个字符要么根本没有返回所以任何人都可以帮我解决这个问题或帮助引导我找到更简单的解决方案? 感谢大家的帮助!
#morse code converter
def main():
code_input = get_input()
morse_code(code_input)
def get_input():
return input('Enter morse code: ')
def morse_code(code_input):
morse_code = [code_input]
convert = ['--..--', '.-.-.-', '..--..', '-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..',
'----.', '.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---' ,'-.-', '.-..', '--', '-.', '---',
'.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.-', '--..']
new = [',', '.', '?', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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',]
print(morse_code)
length = len(morse_code)
for x in range(length):
for value in range(39):
if morse_code[x] == convert[value]:
print(new[value])
main()
最佳答案
您使用split 的想法应该可以正常工作:
>>> '... ---.. -. -.. .... . .-.. .--.'.split()
['...', '---..', '-.', '-..', '....', '.', '.-..', '.--.']
对于翻译,我会使用字典而不是列表:
morse2text = {'...': 's', '---': 'o'}
为避免键错误,我会使用字典 get() 进行“安全查找”方法:
print( morse2text.get(m, m) )
这里是所有代码放在一起(虽然有一个不完整的字典),以防你想要构建一个工作示例:
morse2text = {
'.-': 'a',
'-..': 'd',
'.': 'e',
'....': 'h',
'..': 'i',
'-.': 'n',
'---': 'o',
'...': 's',
'-': 't',
}
s = '... ---.. -. -.. .... . .-.. .--.'
for m in s.split():
print( morse2text.get(m, m) )
关于Python 摩尔斯电码 : S. O.S,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42358657/