Python 摩尔斯电码 : S. O.S

标签 python algorithm parsing search

我在完成这段代码时遇到了问题。我最初的计划是接受一个长字符串作为输入,例如 '... ---.. -. - .. .. .-. .--'然后能够使用 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/

相关文章:

java - 广义序列模式发现的库/框架?

python - 使用 python 解析多行 whatsapp 文本不起作用

python - Flask 和 Flask-SocketIO

python - Scrapy - 上传到 S3 时如何为一个项目中的多个文件 URL 设置自定义路径?

algorithm - 如何判断向 DAG 中添加边是否形成有向循环?

Java CSV 文件操作

c++ - 用 while(cin >> x) 填充 std::vector<int> 的问题

Python List Comprehensions - 加入 For 循环

python - 如何在 matplotlib 饼图中设置楔形边框?

php - 订单履行优化算法