摩尔斯电码(又译为摩斯密码,Morse code)是一种时通时断的信号代码,通过不同的排列顺序来表达不同的英文字母、数字和标点符号。
摩斯编码:
1、加密方法
2、解密方法
要求:解密的时候要求能够自动识别间隔符,如空格,“\”等。
解密的时候能够自动识别出配对字符,如0和1,.和-。
加密的时候能够自定义区分间隔的符号,默认输出空格。
摩斯密码解密加密Python脚本如下:
'''
摩斯编码解码模块
@author Liao
@time 2020-1-19
'''
class Morse:
'''
__decode_MorseList解密字典
__encode_MorseList加密字典
encode加密函数
decode解密函数
Output输出函数
'''
__decode_MorseList = {
#26个字母
".-": "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",
#10个数字
"-----": "0", ".----": "1", "..---": "2", "...--": "3", "....-": "4", ".....": "5",
"-....": "6", "--...": "7", "---..": "8", "----.": "9",
#16个字符
".--.-":"(", '-.--.-':')',"-....-":"-","..--..":"?", "-..-.": "/", ".-.-.-": ".",
".--.-.":"@",'...-..-':'$',"---...":":","--..--":",","-.-.-.":";",".----.":"'",
"-...-":"=","-.-.--":"!",".-...":"&",".-.-.":"+"
}#解密字典
__encode_MorseList = dict([values, key] for key, values in __decode_MorseList.items())# 加密字典
def encode(self, plaintext="",sign=' '):# 加密函数
'''
对输入的字符串进行加密
args={
plaintext: 用于加密的明文字符串
sign:自定义的间隔符
}
'''
charlist = list(plaintext.upper())# 将明文中的字母转换成大写
morsecode=''# 需要转换成的密文
for char in charlist:
if char in self.__encode_MorseList.keys():# 明文的字母在字典的键中
morsecode+=self.__encode_MorseList[char]
morsecode+=sign
elif char==' ':# 明文中的空格
continue
else:# 其他
morsecode="error plaintext!"
break
self.Output(morsecode)
def decode(self, morsecode): #解密函数
'''
用于对输入的密文进行解密
args={
morsecode:需要解密的密文
}
'''
plaintext=''# 需要转换成的明文
morsecode=morsecode.replace("0",".")# 将密文中的字符转换成.和-
morsecode=morsecode.replace("1","-")
l=len(morsecode)# 密文的长度
i=0
while i<l:# 找出间隔符
if morsecode[i].__eq__(".")or morsecode[i].__eq__("-"):
i+=1
else:
sign = morsecode[i]
break;
morsecodeList = morsecode.split(sign)
for key in morsecodeList:
plaintext+=self.__decode_MorseList[key]
self.Output(plaintext)
def Output(self,string):
'''
用于输出数据
args={
string:将要输出的数据
}
'''
print(string)
if __name__ == "__main__":
mc = Morse()
plaintext= input("请输入你需要加密的明文:")
mc.encode(plaintext)
morsecode = input("请输入你需要解密的摩斯密码:")
mc.decode(morsecode)