我正在编写一个将普通文本翻译成摩尔斯电码的程序,而且我编写了将单个字母翻译成摩尔斯电码的核心程序,我仍然无法弄清楚如何翻译整个单词和文本。
更多澄清: 我可以翻译单个字母,但我无法翻译整个单词
以下是代码:
from tkinter import *
#key down function
def click():
entered_text=textentry.get() #this wil collect the text from the text entry box
outpout.delete(0.0, END)
try:
definition = my_dictionary[entered_text]
except:
definition= "sorry an error occured"
outpout.insert(END, definition)
#### main
window = Tk()
window.title("THIS IS A SIMPLE TITLE")
window.configure(background="yellow")
#create label
Label (window,text="Enter a text here.", bg="YELLOW", fg="BLACK", font="arial 30 bold italic" ) .grid(row=1, column=0, sticky=W)
#create a text entry box
textentry= Entry(window, width=20, bg="WHITE")
textentry.grid(row=2, column=0, sticky=W)
#add a submit button
Button(window, text="SUBMIT", width=6, command=click) .grid(row=3 ,column=0, sticky=W)
#create another label
Label (window,text="THE ENCRYPTED TEXT IS:", bg="YELLOW", fg="BLACK", font="arial 10 bold" ) .grid(row=4, column=0, sticky=W)
#create a text box
outpout = Text(window, width=75, height=6, wrap=WORD, bg="WHITE")
outpout.grid(row=5, column=0, columnspan=2, sticky=W)
#the dictionary
my_dictionary = {
"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" : "--..",
" " : "/"
}
#run the main loop
window.mainloop()
答案 0 :(得分:0)
你只需要迭代整个句子,使用你的字典来翻译和积累结果,例如列表理解:
sentence = "Hello World"
[my_dictionary[s] for s in sentence.upper()]
# Out: ['....', '.', '.-..', '.-..', '---', '/', '.--', '---', '.-.', '.-..', '-..']
如果您需要一个字符串作为结果,您可以加入列表,其中包含单个翻译和join
以及您选择的分隔符,例如" |"这里:
"|".join([my_dictionary[s] for s in sentence.upper()])
# Out: '....|.|.-..|.-..|---|/|.--|---|.-.|.-..|-..'
答案 1 :(得分:0)
我认为问题在于您尝试将整个文本用作字典的关键字。因此,如果文本“A”输入到文本输入中,那么它的作用是“A”是my_dictionary
中的键。如果在文本框中输入文本“AS”,则会失败,因为my_dictionary
中没有关键字“AS”。
因此,您要做的是循环输入字符串中的每个字符,并将该字母的莫尔斯值添加到您的定义字符串中。您还需要确保该字母为大写(除非保证输入为大写)。这是使用以下示例中的字符串.upper()
方法完成的。像下面这样的东西应该做你想要的。
definition = str() # Create a blank string to add the Morse code to
# Go through each letter and add the Morse definition of the letter to definition
for letter in entered_text:
definition += my_dict[letter.upper()] # The upper makes sure the letter is a capital so that there will be a match in my_dict