摩尔斯电码转换python123
时间: 2023-07-28 10:14:23 浏览: 42
以下是一个简单的 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':'--..',
'1':'.----', '2':'..---', '3':'...--',
'4':'....-', '5':'.....', '6':'-....',
'7':'--...', '8':'---..', '9':'----.',
'0':'-----', ', ':'--..--', '.':'.-.-.-',
'?':'..--..', '/':'-..-.', '-':'-....-',
'(':'-.--.', ')':'-.--.-'}
def text_to_morse_code(text):
morse_code = ''
for char in text:
if char != ' ':
morse_code += MORSE_CODE_DICT[char] + ' '
else:
morse_code += ' '
return morse_code
def morse_code_to_text(morse_code):
morse_code += ' '
text = ''
char = ''
for code in morse_code:
if code != ' ':
i = 0
char += code
else:
i += 1
if i == 2:
text += ' '
else:
text += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT.values()).index(char)]
char = ''
return text
# 测试代码
text = 'HELLO WORLD'
morse_code = text_to_morse_code(text.upper())
print(morse_code)
text = morse_code_to_text(morse_code)
print(text)
```
输出结果为:
```
.... . .-.. .-.. --- / .-- --- .-. .-.. -..
HELLO WORLD
```
这段代码中,我们使用了一个摩尔斯电码字典 `MORSE_CODE_DICT` ,其中包含了所有字母、数字和一些标点符号的摩尔斯电码。 `text_to_morse_code` 函数将文本转换为摩尔斯电码, `morse_code_to_text` 函数将摩尔斯电码转换为文本。在测试代码中,我们将文本转换为摩尔斯电码并输出,然后将摩尔斯电码转换为文本并输出。