python 用于编码/解码莫尔斯码的python代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 用于编码/解码莫尔斯码的python代码相关的知识,希望对你有一定的参考价值。

    morseAlphabet ={
        "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" : "--..",
        " " : "/"
        }

    inverseMorseAlphabet=dict((v,k) for (k,v) in morseAlphabet.items())


    testCode = ".... . .-.. .-.. --- / -.. .- .. .-.. -.-- / .--. .-. --- --. .-. .- -- -- . .-. / --. --- --- -.. / .-.. ..- -.-. -.- / --- -. / - .... . / -.-. .... .- .-.. .-.. . -. --. . ... / - --- -.. .- -.-- "

    # parse a morse code string positionInString is the starting point for decoding
    def decodeMorse(code, positionInString = 0):
        
        if positionInString < len(code):
            morseLetter = ""
            for key,char in enumerate(code[positionInString:]):
                if char == " ":
                    positionInString = key + positionInString + 1
                    letter = inverseMorseAlphabet[morseLetter]
                    return letter + decodeMorse(code, positionInString)
                
                else:
                    morseLetter += char
        else:
            return ""
        
    #encode a message in morse code, spaces between words are represented by '/'
    def encodeToMorse(message):
        encodedMessage = ""
        for char in message[:]:
            encodedMessage += morseAlphabet[char.upper()] + " "
                
        return encodedMessage

以上是关于python 用于编码/解码莫尔斯码的python代码的主要内容,如果未能解决你的问题,请参考以下文章

python验证码解码器库

python中的base64加密解密

python开发中编码相关问题

opencv python图片编码解码

python使用base64编码解码数据

Python5 - 字符编码