莫尔斯电码是一种将文本信息作为一系列开,关的音调,灯光或咔嗒声进行传输的方法,熟练的听众或观察者无需特殊设备即可直接理解。它以电报的发明者塞缪尔·FB·莫尔斯(Samuel FB Morse)的名字命名。
算法
该算法非常简单。英文中的每个字符都由一系列的“点”和“破折号”代替,有时只是单数的“点”或“破折号”,反之亦然。
加密
解密方式
执行
Python提供了一种称为字典的数据结构,该结构以键值对的形式存储信息,这对于实现密码(例如莫尔斯电码)非常方便。我们可以将莫尔斯电码表保存在字典中,其中(键值对)=>(英文字符-摩尔斯电码)。明文(英文字符)代替密钥,密文(摩尔斯码)形成相应密钥的值。可以从字典中访问键的值,就像我们通过它们的索引访问数组的值一样,反之亦然。
'''
VARIABLE KEY
'cipher' -> 'stores the morse translated form of the english string'
'decipher' -> 'stores the english translated form of the morse string'
'citext' -> 'stores morse code of a single character'
'i' -> 'keeps count of the spaces between morse characters'
'message' -> 'stores the string to be encoded or decoded'
'''
MORSE_CODE_DICT = { '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':'--..',
'1':'.----', '2':'..---', '3':'...--',
'4':'....-', '5':'.....', '6':'-....',
'7':'--...', '8':'---..', '9':'----.',
'0':'-----', ', ':'--..--', '.':'.-.-.-',
'?':'..--..', '/':'-..-.', '-':'-....-',
'(':'-.--.', ')':'-.--.-'}
def encrypt(message):
cipher = ''
for letter in message:
if letter != ' ':
cipher += MORSE_CODE_DICT[letter] + ' '
else:
cipher += ' '
return cipher
def decrypt(message):
message += ' '
decipher = ''
citext = ''
for letter in message:
if (letter != ' '):
i = 0
citext += letter
else:
i += 1
if i == 2 :
decipher += ' '
else:
decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT
.values()).index(citext)]
citext = ''
return decipher
def main():
message = "GEEKS-FOR-GEEKS"
result = encrypt(message.upper())
print (result)
message = "--. . . -.- ... -....- ..-. --- .-. -....- --. . . -.- ... "
result = decrypt(message)
print (result)
if __name__ == '__main__':
main()
输出:
-。。。-.- ... -....- ..- -.. -....--。。。-.- ...
GEEKS-FOR-GEEKS