摩尔斯电码转换 python
时间: 2024-12-08 14:21:27 浏览: 84
摩尔斯电码是一种早期的通信编码方式,通过长短音符代表字母和数字。在Python中,你可以创建一个函数来实现从文本到摩尔斯电码,以及反过来的解码。这里是一个简单的示例:
```python
# 定义摩尔斯电码字典
morse_code_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': '----.'
}
def encode_morse(text):
morse_text = ''
for char in text.upper():
if char.isalpha():
morse_text += morse_code_dict[char] + ' '
elif char.isdigit():
morse_text += morse_code_dict[char] + ' '
else:
morse_text += char # 如果不是字母或数字,保持原样
return morse_text.strip() # 删除末尾空格
def decode_morse(morse_code):
decoded_text = ''
words = morse_code.split(' ') # 每两个空格分隔一个单词
for word in words:
for letter in word.split(' '):
decoded_text += list(morse_code_dict.keys())[list(morse_code_dict.values()).index(letter)]
decoded_text += ' ' # 字符间添加空格
return decoded_text.strip()
# 示例
text = "Hello World!"
encoded = encode_morse(text)
print(f"Encoded Morse: {encoded}")
decoded = decode_morse(encoded)
print(f"Decoded Text: {decoded}")
阅读全文
相关推荐














