簡體   English   中英

Python:類型錯誤:序列項 0:預期的 str 實例,找到無類型

[英]Python: TypeError: sequence item 0: expected str instance, NoneType found

試圖將莫爾斯電碼輸入轉換回英文。


morse_code = { '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' : "--.. ",
               '0' : "----- ",
               '1' : ".---- ",
               '2' : "..--- ",
               '3' : "...-- ", 
               '4' : "....- ",
               '5' : "..... ",
               '6' : "-.... ", 
               '7' : "--... ",
               '8' : "---.. ",
               '9' : "----. ", 
               ' ' : "  "
}

# reverse key
morse_code_reverse = {value:key for key,value in morse_code.items()}

function 試圖將莫爾斯電碼輸入轉換回英文

def revert_morse_code_dictionary(text):
    return ''.join(morse_code_reverse.get(i) for i in text.split())

主要的

if __name__ == "__main__":
    cont = True
    while cont:
        text = input("Please enter a line of morse code text. Enter an empty line to stop.\n")
        print(revert_morse_code_dictionary(text))
        if text != "":
            print(decode_morse(text))
        else:
            cont = False

為什么這會不斷返回此錯誤? 當輸入沿線

-.-. .- -. -.-- --- ..- .-. . .- -.. -- .
in revert_morse_code_dictionary
    return ''.join(morse_code_reverse.get(i) for i in text.split())
TypeError: sequence item 0: expected str instance, NoneType found

def revert_morse_code_dictionary(text):
     return ''.join(morse_code_reverse.get(i) for i in text.split())

您的第一個操作是拆分輸入字符串,以便您擁有

["-.-.", ".- -.", "-.--"...]

split操作會刪除所有空格。 但是字典中的所有元素最后都包含一個空格。 例如

"C": "-.- ."

將不匹配第一項-.-. . 由於后者不匹配任何鍵,因此get()將返回None

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM