python模仿声音_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程序设计有所帮助。

摩斯是一种将字母和数字转换成一系列点和划的编方式,可以通过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 encrypt(message): cipher = '' for letter in message: if letter != ' ': cipher += MORSE_CODE_DICT[letter.upper()] + ' ' else: cipher += ' ' return cipher def decrypt(message): message += ' ' decipher = '' citext = '' for letter in message: if (letter != ' '): i = 0 citext += letter else: i += 1 if i == 2: decipher += ' ' else: decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT.values()).index(citext)] citext = '' return decipher # 示例 message = "CSDN AI助手" result = encrypt(message) print(result) result2 = decrypt(result) print(result2) ``` 该程序中,我们定义了一个摩斯字典 `MORSE_CODE_DICT`,其中包含了每个字母和数字对应的摩斯。`encrypt()` 函数接受一个字符串作为参数,返回该字符串的摩斯形式。`decrypt()` 函数接受一个摩斯形式的字符串作为参数,返回该字符串的明文形式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值