在做一些課堂作業時遇到問題,我似乎無法獲得回傳正確單詞的功能。
我期待得到“你好!” 但我不斷收到“eeeeee teeeeeaee!”。
這是他們提供的提示:
問題是莫爾斯符號的翻譯順序錯誤。
例如, '。' 這意味著'e'在'....'之前翻譯,這意味著'h'。
結果,“....”不翻譯為“h”,而是翻譯為“eeee”。
因此,要修復翻譯器,首先需要翻譯所有 4 字符符號,然后所有 3 字符符號,然后所有 2 字符符號,最后是兩個 1 字符符號“。” 和 '-'。
分隔符應該在最后完成 - 首先是'||' 應替換為一個空格 ' ',然后是單個分隔符 '|' 帶有空文本字串“”。
def morse2txt(t):
"""Translates Morse code to text"""
t = t.replace(".-", 'a')
t = t.replace("-...", 'b')
t = t.replace("-.-.", 'c')
t = t.replace("-..", 'd')
t = t.replace(".", 'e')
t = t.replace("..-.", 'f')
t = t.replace("--.", 'g')
t = t.replace("....", 'h')
t = t.replace("..", 'i')
t = t.replace(".---", 'j')
t = t.replace("-.-", 'k')
t = t.replace(".-..", 'l')
t = t.replace("--", 'm')
t = t.replace("-.", 'n')
t = t.replace("---", 'o')
t = t.replace(".--.", 'p')
t = t.replace("--.-", 'q')
t = t.replace(".-.", 'r')
t = t.replace("...", 's')
t = t.replace("-", 't')
t = t.replace("..-", 'u')
t = t.replace("...-", 'v')
t = t.replace(".--", 'w')
t = t.replace("-..-", 'x')
t = t.replace("-.--", 'y')
t = t.replace("--..", 'z')
t = t.replace("||", ' ')
t = t.replace("|", '')
return t
# Main program
morse = "....|..||-|....|.|.-.|.|!"
txt=morse2txt(morse)
print(txt)
uj5u.com熱心網友回復:
您需要按照提示進行操作:
因此,要修復翻譯器,首先需要翻譯所有 4 字符符號,然后所有 3 字符符號,然后所有 2 字符符號,最后是兩個 1 字符符號“。” 和 '-'。
所以,這看起來像這樣:
def morse2txt(t):
#First, translate the 4-character symbols
t = t.replace("-...", 'b')
t = t.replace("-.-.", 'c')
t = t.replace("-..", 'd')
t = t.replace("..-.", 'f')
t = t.replace("....", 'h')
t = t.replace(".---", 'j')
t = t.replace(".-..", 'l')
t = t.replace(".--.", 'p')
t = t.replace("--.-", 'q')
t = t.replace("...-", 'v')
t = t.replace("-..-", 'x')
t = t.replace("-.--", 'y')
t = t.replace("--..", 'z')
#Next, translate the 3-character symbols
t = t.replace("-.-", 'k')
t = t.replace("---", 'o')
t = t.replace(".-.", 'r')
t = t.replace("...", 's')
t = t.replace("..-", 'u')
t = t.replace(".--", 'w')
#Then, translate the 2-character symbols
t = t.replace(".-", 'a')
t = t.replace("-.", 'n')
t = t.replace("--.", 'g')
t = t.replace("..", 'i')
t = t.replace("--", 'm')
#After that, translate the 1-character symbols
t = t.replace("-", 't')
t = t.replace(".", 'e')
#Finally, translate the delimiters
t = t.replace("||", ' ')
t = t.replace("|", '')
return t
morse = "....|..||-|....|.|.-.|.|!"
txt = morse2txt(morse)
print(txt)
首先翻譯 4 個字符的符號(如 -...),然后是 3 個字符的符號(如 -.-),然后是 2 個字符的符號(如 .-),然后是 1 個字符的符號 ( - 和 .),最后是分隔符(|| 和 |)。如果您不這樣做,而是在任何其他符號之前執行 1 個字符的符號,它們會破壞它們。例如,在您嘗試的內容中,4 e 被替換為 ah,因為 e 是 . h 是.....,如果你先做 e,它會產生 4 個 e 而不是一個 h。如果您在 3 符號或 4 符號之前執行 2 符號,或者在 4 符號之前執行 3 符號,則會出現同樣的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/528280.html
下一篇:帶有宣告變數的SQL函式
