摩尔斯编码与解码

最近想记忆摩尔斯密码来装装逼,作为检查,写个小程序较为方便。

查表后,设置了编码及解码字典。格式为字母间间隔为1个空格,单词的间隔为2个空格,这样不仅浏览起来方便,编码解码也方便。

# import re
# 摩尔斯电码对应符号
# 编码
chars={'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:'----.','?':'..--..','/':'-..-.','()':'-.--.-','-':'-....-','.':'.-.-.-',',':'..-..',
'!':'..--.',':':'---...',';':'-.-.-','+':'.-.-.','=':'-...-'}
# 解码
reversed_chars={'.-': '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,
 '..--..': '?', '-..-.': '/', '-.--.-': '()', '-....-': '-', '.-.-.-': '.','..-..':',','..--.':'!',
 '---...':':','-.-.-':';','.-.-.':'+','-...-':'='}
def encode(string):
	old_str=string.split()
	result=''
	for ss in old_str:
		for i in ss:
			if i.isdigit():
				result+=chars[int(i)]
			elif i.isalpha() and chars[i.upper()]:
				result+=chars[i.upper()]
			elif i in chars:
				result+=chars[i]
			else:
				result+=i
			result+=' '
		# 单词间多加一个空格
		result+=' '
	return result.rstrip()

def decode(string):
	old_str=string.split(' ')
	result=''
	for i in old_str:
		if i:
			if i in reversed_chars:
				result+=str(reversed_chars[i])
			else:
				result+=i
		# 因为单词间的空格设置为了2个,所以此时为空表示存在空格
		else:
			result+=' '
	# 返回小写格式
	# return result.lower().capitalize()
	return result.lower()
# 测试
s=encode('7 people had fucked you when i went out to buy a cigarette! bitch!!!')
print(s)
ss=decode(s)
print(ss)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章