python编写莫尔斯电码程序
教师节快到了,本人提前给老师送花,在写贺卡的时候想以莫尔斯电码的形式写,但自己一个一个对照太麻烦了,就写了个莫尔斯电码程序
。
代码献上
import winsound
import time
dict1 = {'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': '----.', '.':'.-.-.-',
',':'--..--', '!':'-.-.--', ' ':'---...---', ':':'---...', ';':'-.-.-.',
'?':'..--..', '=':'-...-', '\'':'.----.', '/':'-..-.', '-':'-....-',
'_':'..--.-', '':''}
dict2 = dict(zip(dict1.values(), dict1.keys()))
def encode():
words = input("输入一个你想输入的句子:").strip().lower()
for letter in words:
if letter == '':
print('', end=' ')
else:
for s in dict1[letter]:
print(s, end='')
if s == '.':
winsound.Beep(600,333)
time.sleep(0.1)
else:
winsound.Beep(600,1000)
time.sleep(0.1)
print(' ',end="")
time.sleep(1.5)
print()
def decode():
codes = input("输入要解码的摩尔斯电码,仅限摩尔斯电码:").strip().split(" ")
for sign in codes:
if sign == '/':
print(' ', end='')
else:
print(dict2[sign], end='')
print()
def main():
while 1 == 1:
choice = input("编码(文字到摩尔斯电码)或解码(摩尔斯电码到文字)。请输入[0/1]")
if choice == '0':
encode()
elif choice == '1':
decode()
else:
print(choice + "不是可用的选项")
main()
if __name__=="__main__":
main()