摩斯码解译

 网上看到的题目,试做看看,改天再做一个回摩斯码的

'''
摩斯码在实际编写时,字母与字母间由1个空格进行分割,单词和单词间,由3个空格进行分割
出现在摩斯码首尾的空格均为无效字符
'''
MORSE_CODE = {'.-...': '&', '--..--': ',', '....-': '4', '.....': '5', '...---...': 'SOS', '-...': 'B', '-..-': 'X', '.-.': 'R', '.--': 'W', '..---': '2', '.-': 'A', '..': 'I', '..-.': 'F', '.': 'E', '.-..': 'L', '...': 'S', '..-': 'U', '..--..': '?', '.----': '1', '-.-': 'K', '-..': 'D', '-....': '6', '-...-': '=', '---': 'O', '.--.': 'P', '.-.-.-': '.', '--': 'M', '-.': 'N', '....': 'H', '.----.': "'", '...-': 'V', '--...': '7', '-.-.-.': ';', '-....-': '-', '..--.-': '_', '-.--.-': ')', '-.-.--': '!', '--.': 'G', '--.-': 'Q', '--..': 'Z', '-..-.': '/', '.-.-.': '+', '-.-.': 'C', '---...': ':', '-.--': 'Y', '-': 'T', '.--.-.': '@', '...-..-': '$', '.---': 'J', '-----': '0', '----.': '9', '.-..-.': '"', '-.--.': '(', '---..': '8', '...--': '3'}
# print(MORSE_CODE)

def decodeMorse(code):
    #去除首尾的无效空格
    words = code.strip().split("   ") #再把三个空格分隔的单词分开
    mdecode = ''
    for i in range(len(words)): #对每个单词,再将用一个空格分开的元素分开
        word = words[i].strip().split(" ")
        for j in range(len(word)): #针对每个元素去解码
            mdecode += (MORSE_CODE[word[j]]) #将单词里的每个元素解码以后接在一起
        mdecode +=  ' ' #一个单词接完以后先接一个空格再接后面单词\
    mdecode = mdecode.strip()
    return mdecode
code = '...---...'
print(decodeMorse(code))

  

posted on 2018-01-24 00:06  实用才是硬道理  阅读(633)  评论(0编辑  收藏  举报

导航