英摩互转程序摩尔斯码转英文时报TypeError问题求助
Hey there! Let's break down why your Morse-to-English conversion is throwing that TypeError and fix it step by step.
What's Causing the Error?
The error TypeError: sequence item 0: expected str instance, NoneType found tells us that when you run ''.join(map(trans_back.get, user_input)), one of the values returned by trans_back.get() is None. That happens because:
- Your original
translationdictionary has Morse codes with trailing spaces (like"A": ".- "), so when you createtrans_back(the reversed dictionary), its keys are Morse codes with those extra spaces. - When you split user input Morse code, you're likely getting values without those trailing spaces—so
trans_backcan't find a match and returnsNone, whichstr.join()can't handle (it expects strings only).
How to Fix It
Let's fix this with two key adjustments:
1. Clean Up the Morse Code Dictionary
First, remove the trailing spaces from all Morse code values in your translation dict. This ensures your reversed trans_back uses clean, standard Morse codes as keys:
# Cleaned translation dict (no trailing spaces on Morse codes) translation = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", # Add all other characters here with clean Morse codes }
2. Build the Reversed Dictionary Correctly
Now create trans_back by reversing the cleaned translation dict—this will map valid Morse codes to their English equivalents:
trans_back = {value: key for key, value in translation.items()}
3. Handle User Input Properly
Morse code uses single spaces to separate characters and two spaces to separate words. We need to handle this structure to avoid empty strings and missing matches:
def morse_to_english(user_input): # Split input into words (separated by two spaces) words = user_input.split(" ") english_words = [] for word in words: # Split each word into individual Morse characters, filter out empty strings morse_chars = [char for char in word.split(" ") if char] # Convert each Morse char to English, use '?' for unknown codes english_chars = [trans_back.get(char, '?') for char in morse_chars] english_words.append(''.join(english_chars)) # Join words back into a single string return ' '.join(english_words)
Full Working Example
Putting it all together, here's a complete snippet you can test:
# English to Morse code dictionary (cleaned) 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": "--..", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", ".": ".-.-.-", ",": "--..--", "?": "..--..", "'": ".----.", "!": "-.-.--", "/": "-..-.", "(": "-.--.", ")": "-.--.-", "&": ".-...", ":": "---...", ";": "-.-.-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "_": "..--.-", '"': ".-..-.", "$": "...-..-", "@": ".--.-.", " ": " " } # Reversed dictionary for Morse to English trans_back = {value: key for key, value in translation.items()} def english_to_morse(text): return ' '.join([translation.get(char.upper(), '?') for char in text]) def morse_to_english(user_input): words = user_input.split(" ") english_words = [] for word in words: morse_chars = [char for char in word.split(" ") if char] english_chars = [trans_back.get(char, '?') for char in morse_chars] english_words.append(''.join(english_chars)) return ' '.join(english_words) # Test the functions print(english_to_morse("Hello World!")) # Output: .... . .-.. .-.. --- .-- --- .-. .-.. -.. -.-.-- print(morse_to_english(".... . .-.. .-.. --- .-- --- .-. .-.. -.. -.-.--")) # Output: HELLO WORLD!
Why This Works
- No more trailing spaces in Morse codes means
trans_backhas valid, matching keys for user input. - We handle word separation with two spaces, so words are correctly split and reconstructed.
- Using
trans_back.get(char, '?')preventsNonevalues—unknown Morse codes will show up as?instead of crashing the program.
内容的提问来源于stack exchange,提问作者Hunter T.

