莫尔斯电码允许多个字符

2024-10-01 13:28:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个程序,接受输入,并转换成莫尔斯电码的形式,电脑哔哔声的形式,但我不知道如何使它,以便我可以在输入多个字母,而不会得到错误。在

这是我的代码:

import winsound
import time

morseDict = {
'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': '--..'
}
while True: 
    inp = raw_input("Message: ")
    a = morseDict[inp] 
    morseStr =  a
    for c in morseStr:
        print c
        if c == '-':
            winsound.Beep(800, 500)
        elif c == '.':
            winsound.Beep(800, 100)
        else:
            time.sleep(0.4)  
        time.sleep(0.2)

现在需要一个字母一个字母,但我希望它是短语。在


Tags: 代码import程序电码time错误字母sleep
3条回答

我相信你需要迭代输入中的字母。在

while True: 
    inp = raw_input("Message: ")
    for letter in inp:          # <- Edit in this line
        a = morseDict[letter]   # <- and this one, rest have increased indent
        morseStr =  a
        for c in morseStr:
            print c
            if c == '-':
                winsound.Beep(800, 500)
            elif c == '.':
                winsound.Beep(800, 100)
            else:
                time.sleep(0.4)  
            time.sleep(0.2)
        time.sleep(0.4)        # Or desired time between letters

只需添加一个额外的for循环,然后循环输入中的字符即可获得消息!但别忘了在必要的时候结束你的循环!在

在下面的代码中,我做了这样的事情:在消息被解码后,它会询问你是否想再发送一个,如果你输入“n”,它将退出循环!在

going = True
while going: 
    inp = raw_input("Message: ")
    for i in inp:
        a = morseDict[i] 
        morseStr =  a
        for c in morseStr:
            print c
            if c == '-':
                winsound.Beep(800, 500)
            elif c == '.':
                winsound.Beep(800, 100)
            else:
                time.sleep(0.4)  
            time.sleep(0.2)
    again = raw_input("would you like to send another message? (y)/(n) ")
    if again.lower() == "n":
         going = False

现在你还有一个问题…你没有考虑空间!!所以你还是只能发短信!如果我是对的,单词之间的空格是莫尔斯电码中固定的定时静音,所以我要说的是你应该做的是加上:

^{pr2}$

这样,当试图查找空间实例时,它不会返回错误,它将在else语句中运行,并在下一个单词之前额外添加一个.4秒!在

试着把你的循环改成这样:

while True:
    inp = raw_input("Message: ")
    for char in inp:
        for x in morseDict[char]:
            print x
            if x == "-":
                winsound.Beep(800, 500)
            elif x == ".":
                winsound.Beep(800, 100)
            else:
                time.sleep(0.4)
            time.sleep(0.2)

这样,首先迭代输入中的字符,然后在morseDict中查找字符,然后迭代morseDict[char]的值。在

相关问题 更多 >