










Heya,
Your issues stem from three things: (1) dict[key] raises KeyError on unknown codes, (2) split(" ") produces empty strings when there are consecutive spaces, and (3) you’re not distinguishing letter separators (single space) from word separators (typically / or multiple spaces).
## The fix
### 1. Use dict.get() instead of dict[...]
dict.get(key, default) returns the default instead of raising KeyError. This alone solves the crash on @.
### 2. Standardize the word separator
The conventional Morse convention is:
/) between wordsNormalize the input first so the parser only deals with one format.
### 3. Parse in two levels: words → letters
Split on the word separator first, then on the letter separator. This makes empty tokens disappear naturally and makes the intent explicit.
## Working example
MORSE_CODE_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',
'-----':'0', '.----':'1', '..---':'2', '...--':'3', '....-':'4',
'.....':'5', '-....':'6', '--...':'7', '---..':'8', '----.':'9',
}
def decode_morse(morse: str, unknown: str = '?') -> str:
# Normalize: treat "/" as a word separator, collapse runs of spaces
# into the canonical 3-space word break.
normalized = morse.replace('/', ' ').strip()
words = [w for w in normalized.split(' ') if w]
decoded_words = []
for word in words:
letters = [MORSE_CODE_DICT.get(code, unknown)
for code in word.split(' ') if code]
decoded_words.append(''.join(letters))
return ' '.join(decoded_words)
### Test
>>> decode_morse('.... . .-.. .-.. --- .-- --- .-. .-.. -..')
'HELLO WORLD'
>>> decode_morse('.... . .-.. .-.. --- .-- --- .-. .-.. -.. @')
'HELLO WORLD?'
>>> decode_morse('.... . .-.. .-.. --- / .-- --- .-. .-.. -..')
'HELLO WORLD'
## Why this works
| Problem | Cause | Fix |
|---|---|---|
KeyError on @ |
dict[key] raises on miss |
dict.get(code, '?') |
| Empty decoded chars | "a b".split(" ") yields ['a', '', 'b'] |
if code filter inside the comprehension |
| Words run together | No distinction between letter/word gaps | Split on " " first, then " " |
| Mixed separators | Some sources use /, some use |
Normalize / → " " up front |
## A couple of further notes
?, raise your own ValueError with the offending token — it’s friendlier than a bare KeyError:
if code not in MORSE_CODE_DICT:
raise ValueError(f"Invalid Morse token: {code!r}")
' ' between letters and ' ' (three spaces) between words so a round-trip decode(encode(x)) == x.upper() holds for supported characters.re.split(r' {3,}', morse.strip()) for words and re.split(r' +', word) for letters also collapses runs gracefully if you prefer not to normalize first.This pattern — normalize input → split coarse → split fine → lookup with default — generalizes well to any token-stream decoder, not just Morse.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。