|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 wp231957 于 2024-3-19 14:46 编辑 import time
def morse_code(text):
morse_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': '−−−·',
'.': '·−·−·', ',': '−·−··', '?': '··−··', '/': '−··−·',
'(': '−−···', ')': '−·−··', '&': '··−··', ':': '−····',
';': '·−···', '=': '··−··', '+': '···−·', '-': '····−',
"'": '·−−−·', '"': '··−··', ' ': '·····', '\n': '······'
}
for char in text:
if char.isalpha() or char.isdigit() or char in morse_dict:
code = morse_dict[char.upper()]
for dot in code:
if dot == '·':
print("\b", end="", flush=True)
time.sleep(0.2)
elif dot == '-':
print("\b", end="", flush=True)
time.sleep(0.4)
time.sleep(0.2)
print("\b", end="", flush=True)
time.sleep(0.4)
elif char == ' ':
time.sleep(1)
elif char == '\n':
print()
time.sleep(1)
text = "HELLO WORLD"
morse_code(text)
非常抱歉,我之前的代码存在错误。实际上,我们不需要使用退格符(`\b`)来消除光标前的字符,因为它会导致错误的输出。下面是修复后的代码:import timefrom sys import stdoutdef display_morse_code(char, morse_dict): code = morse_dict[char] for dot in code: if dot == '·': print('.', end='', flush=True) time.sleep(0.2) elif dot == '-': print('-', end='', flush=True) time.sleep(0.4) print(' ', end='', flush=True)def remove_morse_code(text): for _ in text: stdout.write('\b \b') stdout.flush() time.sleep(0.2)def display_text(text, morse_dict): for char in text: display_morse_code(char, morse_dict) time.sleep(1) remove_morse_code(text) print(text, end='', flush=True)text = "HELLO WORLD"morse_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': '-----', '.': '·-·-·', ',': '-··-·', '?': '··--·', '/': '-··-·', '(': '--·--', ')': '-·-·', '&': '··--·', ':': '-····', ';': '·-···', '=': '·····', '+': '···-', '-': '-····', "'": '·---···', '"': '··--··', ' ': ' '}display_text(text, morse_dict)现在,代码应该以正确的方式显示摩斯码,并且在显示完整的字符串后进行清除。非常抱歉之前的错误给您带来困惑,希望这次能解决问题。如果还有其他问题,请随时提问。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
|
|