微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我的莫尔斯电码解码工具找不到任何后续字符?

如何解决为什么我的莫尔斯电码解码工具找不到任何后续字符?

我正在研究摩尔斯电码编码/解码工具。我已经完成了编码器,我正在研究解码器。目前解码函数MorseCodeDecoder(MSG)”可以一次解码一个字母。它通过逐个检查字符串中的每个字符并将它们复制到变量“EncodedLetter”来实现这一点。程序会检查每个字符是否是空格,如果是,则程序会识别出这是字母之间的间隙,例如: MSG = ".... .." -*the function runs*- EncodedLetter = "....". 然后通过字典(使用列表)回搜索该值以查找 EncodedLetter 的键应该是什么,在这种情况下它是“H”,程序还会检查表示两个单词之间空格的双空格。此时,它可能听起来功能齐全;然而,在找到一个编码的字母后,它找不到另一个,所以更早的“.... ..”它找不到“..”,即使我在成功解码一个字母后重置了变量。

MorseCodeDictionary = {' ': ' ','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 MorseCodeEncoder(MSG):
    EncodedMSG = f"""Encoded Message:
"""
    MSG = MSG.upper()
    for i in range(0,len(MSG),1):
        Encode = (MSG[i])
        EncodedMSG = f"{EncodedMSG} {(MorseCodeDictionary.get(Encode))}"
    return EncodedMSG
def MorseCodeDecoder(MSG):
    DecodedMSG = f"""Decoded Message:
"""
    MSG = MSG.upper()
    DecodedWord = ''
    DecodedLetter = ''
    EncodedLetter = ''
    for i in range(0,len(MSG)):
        DecodedLetter = ''
        Decode = (MSG[i])
        try:    
          if (MSG[i + 1]) == ' ':
            EncodedLetter = f"{EncodedLetter + (MSG[i])}"
            DecodedLetter = list(MorseCodeDictionary.keys())[list(MorseCodeDictionary.values()).index(EncodedLetter)]
            DecodedWord = DecodedWord + DecodedLetter
            EncodedLetter = ''
            DecodedMSG = f"{DecodedMSG} {DecodedWord}"

          elif (MSG[i + 1]) + (MSG[i + 2]) == '  ':
                DecodedWord = ''

          else:
            EncodedLetter = f"{EncodedLetter + (MSG[i])}"
            
        except (ValueError,IndexError):
          pass
        
    return DecodedMSG
    
Loop = 1
while Loop == 1:
    Choice = str(input("""[1] Encode,or [2] decode?
"""))
    if Choice == '1':
        MSG = str(input("""Type the message you would like to encode. Do not use puncuation.
"""))
        EncodedMSG = (MorseCodeEncoder(MSG))
        print (EncodedMSG)
    elif Choice == '2':
        MSG = str(input("""Type what you wish to decode.
"""))
        DecodedMSG = (MorseCodeDecoder(MSG))
        print (DecodedMSG)
    else:
        print ('1,or 2')

解决方法

您可以使用 str.join()str.split(),而不是笨拙地附加到字符串并从编码的字符串中挑选出每个字符以形成莫尔斯电码字母!另外,我建议用一个不能作为正确编码字符串一部分的字符来分隔您编码的莫尔斯电码字母,例如 /。这样,您可以确定字符串中的所有空格都是空格,字符串中的所有斜杠都是字母分隔符。首先,让我们定义编码和解码的字典

en_to_morse = {' ': ' ','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': '-----'}

morse_to_en = {v: k for k,v in en_to_morse.items()} # Reverse lookup for encoder

morse_to_en 字典可以简单地通过反转 en_to_morse 字典中的键和值来创建。这两个可以组合使用,因为它们没有任何公共键(除了空格,这并不重要,因为它保持不变),但我将在本示例中将它们分开。

然后,您可以像这样编写编码器函数:

def MorseEncode(msg):
    morse_msg = [] # make an empty list to contain all our morse symbols
    for char in msg.upper(): # Convert msg to uppercase. Then iterate over each character
        morse_char = en_to_morse[char] # Get the translation from the dictionary
        morse_msg.append(morse_char)   # Append the translation to the list
    return '/'.join(morse_msg)   # Join symbols with a '/'

解码器功能正好与编码器功能相反。

def MorseDecode(msg):
    morse_chars = msg.split("/") # Split at '/'
    en_msg = ""                  # Empty message string 
    for char in morse_chars:     # Iterate over each symbol in the split list
        en_char = morse_to_en[char]  # Translate to English
        en_msg += en_char            # Append character to decoded message
    return en_msg  

运行:

encoded = MorseEncode("Hello World") # gives '...././.-../.-../---/ /.--/---/.-./.-../-..'

decoded = MorseDecode(encoded) # gives 'HELLO WORLD'

您会丢失大小写信息,因为摩尔斯电码没有将符号分隔为大写/小写字符。


您也可以将函数编写为单行程序:

def MorseEncode(msg):
    return '/'.join(en_to_morse[char] for char in msg.upper())

def MorseDecode(msg):
    return ''.join(morse_to_en[char] for char in msg.split('/'))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。