摩尔斯电码 是一种通过一系列开关的音调、灯光或咔哒声来传输文本信息的方法,熟练的听众或观察者无需特殊设备即可直接理解。它以电报的发明者塞缪尔·F·B·摩尔斯(Samuel F. B. Morse)的名字命名。
算法原理
该算法非常简单。英语中的每个字符都被替换为一串“点”和“划”,有时仅仅是单个“点”或“划”,反之亦然。
详情请参阅此 Wikipedia <a href="https://en.wikipedia.org/wiki/Morsecode#/media/File:InternationalMorse_Code.svg">图片。
加密过程
- 在加密的情况下,我们每次从单词中提取一个字符(如果不是空格),并将其与我们选择的任何数据结构中存储的相应摩尔斯电码进行匹配(如果你使用 Python 编写,字典在这种情况下会非常有用)。
- 将摩尔斯电码存储在一个将包含我们编码字符串的变量中,然后我们在包含结果的字符串中添加一个空格。
- 在使用摩尔斯电码编码时,我们需要在每个字符之间添加 1 个空格,在每个单词之间添加 2 个连续的空格。
- 如果该字符是空格,则向包含结果的变量添加另一个空格。我们重复此过程,直到遍历整个字符串。
解密过程
- 在解密的情况下,我们首先在要解码的字符串末尾添加一个空格(这将在稍后解释)。
- 现在我们从字符串中不断提取字符,直到没有遇到空格为止。
- 一旦获得空格,我们就会查找提取的字符序列(即我们的摩尔斯电码)对应的英文字符,并将其添加到存储结果的变量中。
- 请记住,跟踪空格是此解密过程中最重要的部分。一旦我们得到 2 个连续的空格,我们将向包含解码字符串的变量添加另一个空格。
- 字符串末尾的最后一个空格将帮助我们识别最后一段摩尔斯电码字符序列(因为空格充当了提取字符并开始解码的检查标志)。
实现方式:
Python 提供了一种称为字典的数据结构,它以键值对的形式存储信息,这对于实现摩尔斯电码等密码非常方便。我们可以将摩尔斯电码图表保存在字典中,其中 (键值对) => (英文字符 – 摩尔斯电码)。明文(英文字符)占据键的位置,密文(摩尔斯电码)构成相应键的值。我们可以像通过索引访问数组值一样从字典中访问键的值,反之亦然。
Python3
“
目录
Python program to implement Morse Code Translator
‘‘‘
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‘
‘‘‘
Dictionary representing the morse code chart
MORSECODEDICT = { ‘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‘:‘—–‘, ‘, ‘:‘–..–‘, ‘.‘:‘.-.-.-‘,
‘?‘:‘..–..‘, ‘/‘:‘-..-.‘, ‘-‘:‘-….-‘,
‘(‘:‘-.–.‘, ‘)‘:‘-.–.-‘}
Function to encrypt the string
according to the morse code chart
def encrypt(message):
cipher = ‘‘
for letter in message:
if letter != ‘ ‘:
# Looks up the dictionary and adds the
# corresponding morse code
# along with a space to separate
# morse codes for different characters
cipher += MORSECODEDICT[letter] + ‘ ‘
else:
# 1 space indicates different characters
# and 2 indicates different words
cipher += ‘ ‘
return cipher
Function to decrypt the string
from morse to english
def decrypt(message):
# extra space added at the end to access the
# last morse code
message += ‘ ‘
decipher = ‘‘
citext = ‘‘
for letter in message:
# checks for space
if (l