python实现带声音的摩斯码翻译实现方法

本文实例讲述了python实现带声音的摩斯码翻译程序,分享给大家供大家参考。具体分析如下:

这里需要使用pygame来发出声音。

import pygame
import time
import sys
code = {‘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’: ‘—-.’
}
one_unit = 0.5
three_units = 3 * one_unit
seven_units = 7 * one_unit
path = ‘morse_sound_files/’
def verify(string):
keys = code.keys()
for char in string:
if char.upper() not in keys and char != ‘ ‘:
sys.exit(‘error the charcter ‘ + char + ‘ cannot be translated to morse code’)
def main():
print ‘welcome to alphabet to morse code translator v.01\n’
msg = raw_input(‘enter message: ‘)
verify(msg)
print
pygame.init()
for char in msg:
if char == ‘ ‘:
print ‘ ‘*7,
time.sleep(seven_units)
else:
print code[char.upper()],
pygame.mixer.music.load(path + char.upper() + ‘_morse_code.ogg’)
pygame.mixer.music.play()
time.sleep(three_units)
if __name__ == “__main__”:
main()

希望本文所述对大家的python程序设计有所帮助。

Posted in 未分类

发表评论