1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| class MorseCipher: def __init__(self): self.morse_map = { '.-': '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',
'.-.-.-': '.', '--..--': ',', '..--..': '?', '-.-.--': '!', '.-.-.': '+', '-....-': '-', '-..-.': '/', '-...-': '=', '-.--.': '(', '-.--.-': ')', '.----.': "'", '.-..-.': '"' } self.morse_map2 = dict(zip(self.morse_map.values(), self.morse_map.keys()))
def encryption(self, plaintext, sign): ''' 加密函数 ''' cyphertext = [] for i in plaintext: i = i.upper() if i in self.morse_map2.keys(): cyphertext.append(self.morse_map2[i]) cyphertext.append(sign) else: print(i, 'meet error.') return ''.join(cyphertext[:-1])
def decryption(self, cyphertext, sign): ''' 解密函数 ''' cyphertext_list = cyphertext.split(sign) plaintext = [] for i in cyphertext_list: if i in self.morse_map.keys(): plaintext.append(self.morse_map[i]) else: print(i, 'meet error.') return ''.join(plaintext)
t_plain = '12.25HappyBirthday!' t = MorseCipher() print('明文是:', t_plain) t_cypher = t.encryption(t_plain, '/') print('密文是:', t_cypher) t_result = t.decryption(t_cypher, '/') print('解密结果是:', t_result)
|