|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +@author: 闲欢 |
| 5 | +""" |
| 6 | + |
| 7 | +# 表示摩斯密码图的字典 |
| 8 | +MORSE_CODE_DICT = { |
| 9 | + 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', |
| 10 | + 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', |
| 11 | + 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', |
| 12 | + 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', |
| 13 | + 'X': '-..-', 'Y': '-.--', 'Z': '--..', |
| 14 | + '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', |
| 15 | + '7': '--...', '8': '---..', '9': '----.', '0': '-----', |
| 16 | + ', ': '--..--', '.': '.-.-.-', '?': '..--..', '/': '-..-.', '-': '-....-', |
| 17 | + '(': '-.--.', ')': '-.--.-' |
| 18 | + } |
| 19 | + |
| 20 | + |
| 21 | +# 根据摩斯密码图对字符串进行加密的函数 |
| 22 | +def encrypt(message): |
| 23 | + cipher = '' |
| 24 | + for letter in message: |
| 25 | + if letter != ' ': |
| 26 | + # 查字典并添加对应的摩斯密码 |
| 27 | + # 用空格分隔不同字符的摩斯密码 |
| 28 | + cipher += MORSE_CODE_DICT[letter] + ' ' |
| 29 | + else: |
| 30 | + # 1个空格表示不同的字符 |
| 31 | + # 2表示不同的词 |
| 32 | + cipher += ' ' |
| 33 | + return cipher |
| 34 | + |
| 35 | + |
| 36 | +# 将字符串从摩斯解密为英文的函数 |
| 37 | +def decrypt(message): |
| 38 | + # 在末尾添加额外空间以访问最后一个摩斯密码 |
| 39 | + message += ' ' |
| 40 | + decipher = '' |
| 41 | + citext = '' |
| 42 | + global i |
| 43 | + for letter in message: |
| 44 | + # 检查空间 |
| 45 | + if letter != ' ': |
| 46 | + i = 0 |
| 47 | + # 在空格的情况下 |
| 48 | + citext += letter |
| 49 | + # 在空间的情况下 |
| 50 | + else: |
| 51 | + # 如果 i = 1 表示一个新字符 |
| 52 | + i += 1 |
| 53 | + # 如果 i = 2 表示一个新单词 |
| 54 | + if i == 2: |
| 55 | + # 添加空格来分隔单词 |
| 56 | + decipher += ' ' |
| 57 | + else: |
| 58 | + # 使用它们的值访问密钥(加密的反向) |
| 59 | + decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT.values()).index(citext)] |
| 60 | + citext = '' |
| 61 | + return decipher |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | +def main(): |
| 66 | + message = "I LOVE YOU" |
| 67 | + result = encrypt(message.upper()) |
| 68 | + print(result) |
| 69 | + |
| 70 | + message = ".. .-.. --- ...- . -.-- --- ..-" |
| 71 | + result = decrypt(message) |
| 72 | + print(result) |
| 73 | + |
| 74 | + |
| 75 | +# 执行主函数 |
| 76 | +if __name__ == '__main__': |
| 77 | + main() |
0 commit comments