我正在开发莫尔斯电码编码/解码工具。我已经完成了编码器,我正在做解码器。目前,解码功能“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')
您可以使用^{} 和^{} 来代替在字符串后面添加字符并从编码的字符串中挑出每个字符以形成莫尔斯电码字母的笨拙操作!此外,我建议用不能作为正确编码字符串的一部分的字符(如^{)来分隔编码的莫尔斯电码字母。这样,您就可以确保字符串中的所有空格都是空格,并且字符串中的所有斜杠都是字母分隔符。首先,让我们定义编码和解码的字典
只需反转
en_to_morse
字典中的键和值,即可创建morse_to_en
字典。这两个键可以组合在一起,因为它们没有任何公共键(除了空格,这并不重要,因为它保持不变),但在本例中,我将把它们分开然后,您可以这样编写编码器函数:
解码器功能与编码器功能正好相反
要运行此操作,请执行以下操作:
您丢失了大小写信息,因为摩尔斯电码没有区分大小写字符的符号
您也可以将函数编写为一行程序:
相关问题 更多 >
编程相关推荐