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

2024-09-27 07:33:20 发布

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

我正在开发莫尔斯电码编码/解码工具。我已经完成了编码器,我正在做解码器。目前,解码功能“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')

Tags: 程序字母msg解码encode空格choicestr
1条回答
网友
1楼 · 发布于 2024-09-27 07:33:20

您可以使用^{}^{}来代替在字符串后面添加字符并从编码的字符串中挑出每个字符以形成莫尔斯电码字母的笨拙操作!此外,我建议用不能作为正确编码字符串的一部分的字符(如^{)来分隔编码的莫尔斯电码字母。这样,您就可以确保字符串中的所有空格都是空格,并且字符串中的所有斜杠都是字母分隔符。首先,让我们定义编码和解码的字典

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

只需反转en_to_morse字典中的键和值,即可创建morse_to_en字典。这两个键可以组合在一起,因为它们没有任何公共键(除了空格,这并不重要,因为它保持不变),但在本例中,我将把它们分开

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

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('/'))

相关问题 更多 >

    热门问题