簡體   English   中英

為什么我的摩爾斯電碼解碼工具找不到任何后續字符?

[英]Why does my Morse Code decoding tool not find any subsequent characters?

我正在研究摩爾斯電碼編碼/解碼工具。 我已經完成了編碼器,我正在研究解碼器。 目前解碼 function“ 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字典。 這兩個可以組合,因為它們沒有任何公共鍵(除了空格,這並不重要,因為它保持不變),但我將在這個例子中將它們分開。

然后,您可以像這樣編寫編碼器 function:

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

解碼器 function 與編碼器 function 正好相反。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM