将莫尔斯电码翻译为英语,而无需添加额外的格言 [英] Translating morse code to English without adding an extra dict

查看:71
本文介绍了将莫尔斯电码翻译为英语,而无需添加额外的格言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个英语到莫尔斯电码,反之亦然.我成功地将其翻译成莫尔斯电码,但是将莫尔斯电码译成英语时遇到了麻烦.每当我尝试将摩尔斯电码翻译为英语时,都会给我一个TypeError:"text =" .join(map(trans_back.get,user_input)) TypeError:序列项0:预期的str实例,找不到NoneType."

I am making an English to Morse code and vise-versa program. I successfully made it translate English to Morse code but am having a trouble translating Morse code to English. Whenever I try to translate Morse code to English, it gives me a TypeError: "text = ''.join(map(trans_back.get, user_input)) TypeError: sequence item 0: expected str instance, NoneType found".

到目前为止,这是我的代码.最后一部分是我遇到麻烦的代码部分:

Here is my code so far. The last section is the part of the code where I am having trouble:

translation = {
"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": "----- ",
".": ".-.-.- ",
",": "--..-- ",
"?": "..--.. ",
"!": "..--. ",
"/": "-..-. ",
"@": ".--.-. ",
" ": " "
}

user_input = input("Input english or morse code message:\n").upper()

if all(c in translation for c in user_input):
    morse = ''.join(map(translation.get, user_input))
    print(morse)
elif all(c in ".- " for c in user_input):
    print("*needs work in order to change morse to text*")
    #trans_back = {v: k for k, v in translation.items()}
    #text = ''.join(map(trans_back.get, user_input))
    #print(text)

推荐答案

两个块之间的区别在于,第一个块需要逐字符映射,但是第二个块需要将一个字符块映射到一个键.您需要沿空格将user_input拆分,以便map将功能应用于代表单个键的.-组.当然,您还需要从反向字典查找中删除空格.这是我要工作的代码:

The difference between the two blocks is that the first block expects a character-by-character mapping, but the second block requires a block of characters to be mapped to a single key. You need to split user_input along the spaces so map will apply the function to a group of .s and -s representing a single key. Of course then you will also need to remove the spaces from your reversed dictionary lookup. Here's the code that I got to work:

elif all(c in ".- " for c in user_input):
    trans_back = {v.rstrip(' '): k for k, v in translation.items()}
    text = ''.join(map(trans_back.get, user_input.split(' ')))
    print(text)

这篇关于将莫尔斯电码翻译为英语,而无需添加额外的格言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆