python-摩斯码转换

 

意义:简单实现摩斯码的破译和生成

代码:

#-*- coding: UTF-8 -*-

__author__ = '007'
__date__ = '2016/2/2'

import pprint
import re


chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
codes = """.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-..
-- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..
.---- ..--- ...-- ....- ..... -.... --... ---.. ----. -----"""

dd = dict(zip(chars.lower(),codes.split()))
DD = dict(zip(codes.split(),chars.lower()))

#pprint.pprint(DD)

def chars2morse(char):
    return dd.get(char.lower(),' ')

def morse2chars(morse):
    return DD.get(morse,' ')

while True:
    str = raw_input()
    x = str.split(' ')
    ccc = ''.join(x)
    if re.match('^[0-9a-zA-Z]+$',ccc):
        print ' '.join(chars2morse(c) for c in ccc)
    else:
        cc = str.split()
        print ' '.join(morse2chars(c) for c in cc)

运行结果:

python-摩斯码转换_第1张图片

 

你可能感兴趣的:(python-摩斯码转换)