摩尔斯电码简介
摩尔斯在发明一台可以通过电流传递信息的电报机的过程中,为了解决信息编码问题,他和他的助手最后想到对字母直接进行编码,这种做法相比之前的做法效率高。他们用“·”和“-”对字母进行编码。
摩尔斯电码也被称作摩斯密码。摩尔斯电码只使用零和一两种状态的二进制代码。
它的代码包括五种:
- 短促的点信号“・”,读“滴”(Di)
- 保持一定时间的长信号“-”,读“嗒”(Da)
- 表示点和划之间的停顿
- 每个词之间中等的停顿
- 以及句子之间长的停顿
可能你会问,那如何区分打完了一个单词,或者一个语句呢?其实他们也设置的标准的间隔时间:
t代表单位时间间隔,滴=1t,嗒=3t,滴嗒间=1t,字符间=3t,单词间=7t。
标准的摩尔斯电码对照表
python实现摩尔斯电码转换
下面使用python实现摩尔斯编码和解码
# encoding: utf-8
"""
@description: morse编码与解码
@author: baola
@time: 2020-06-04 22:02
@file: morseCode.py
@version: python3.8.1
"""
a2mo_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': '--..',
'0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-',
'5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.'
}
mo2a_dict = dict(zip(a2mo_dict.values(), a2mo_dict.keys()))
def start():
"""
程序入口
:return: NULL
"""
choose = input("编码请按1,解码请按 0")
if choose == "1":
try:
mo2a()
except:
print("请输入格式正确的摩尔斯电码")
if choose == "0":
try:
a2mo()
except:
print("只能输入字母数字")
def mo2a():
"""
摩尔斯电码转换为字符串
:return: NULL
"""
crypto_text = input("请输入摩尔斯电码:")
morse_key = crypto_text.strip().split(" ")
plain_text = [mo2a_dict[key] for key in morse_key]
plain_text = "".join(plain_text)
print("摩尔斯解码后的明文为:", plain_text)
def a2mo():
"""
字符串编码成摩尔斯电码
:return: NULL
"""
crypto_text = ""
plain_text = input("请输入要加密的明文:").strip().replace(" ", "")
for word in plain_text:
crypto_text += a2mo_dict[word] + " "
print("编码后的摩尔斯电码为:", crypto_text)
start()