我正在尝试使用我使用的字典将摩尔斯电码翻译成英文。我试图在用户输入消息的地方使用它,它会将他/她的消息打印成莫尔斯电码。
我发现很容易翻译成摩尔斯电码,但摩尔斯电码英语代码给我带来了一些问题。
首先,如果我输入' .-'为了' A'我实际上得到了E'而是因为它正在阅读第一个'。密钥并将其翻译成“E'而不是拿整个字符串。
这是我到目前为止所尝试的:)
#If user types 'N' or 'n' it proceeds this loop
if morse_message == 'N' or morse_message == 'n': #Loops looks to see if morse_message was 'N' or 'n'
nomorse = input("Enter your Morse code here:")
nomorse_list = (nomorse.join('')
for letter in nomorse_list:
not_morse = (morse_eng_dict[letter.upper()])
print(not_morse)
这是我的词典
morse_eng_dict = {".-": "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"}
我想让Python使用我的莫尔斯代码并将消息打印回英文。比如...... .- ..- .. ---(这是你好)
这是一个项目,所以我不能使用任何花哨的模块或任何东西。 任何想法或输入?谢谢!
答案 0 :(得分:0)
运算符倾向于使用空格来分隔字母和单词: https://en.wikipedia.org/wiki/Morse_code
"单词的字母用等于三个点(一个破折号)的空格分隔,单词用等于七个点的空格分隔。"如果你插入空格,例如:字母之间的1个空格和单词之间的2个空格,进入你的莫尔斯代码字符串,这将解码一块蛋糕(拆分然后映射)
答案 1 :(得分:0)
这样的事情应该有效: 基本上,它会在有空格时拆分字符串,制作一个列表,其中每个项目都是莫尔斯代码字母。然后它会根据字典检查每个字母,然后选择英文字母。最后,它将所有这些放入一个列表中,再次将其转换为字符串并打印出来。 希望它有所帮助!
morse_eng_dict = {".-": "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"}
nomorse = input("Enter your Morse code here:")
nomorse_list = nomorse.split() #this splits the string up wherever there is a space
not_morse = []
morse = True #The code is morse (so far)
for letter in nomorse_list:
eng_letter = False
for key in morse_eng_dict.keys(): #for each of the morse code letters in the dictionary
if letter == key:
eng_letter = morse_eng_dict[key]
if eng_letter: #if a letter was found that corresponds
not_morse.append(eng_letter)
else:
print("Input is not valid morse code.")
morse = False
if morse == True:
string = "".join(not_morse) #joining the string together (without spaces in between)
print(string)
答案 2 :(得分:0)
对于任何dictionary = {'.-': 'a'}
dictionary['.-'] 会给你 'a'
另外 dictionary.get('.-') 也会给你一个 'a'
字典的索引是字符串、任何字符串和 '.'不同于'.-'
'.','.-','...','-.--'
btw morse 是一棵二叉树,以 E = left.node 和 T = right.node ...