將如 "two hundred thirty two"、"nineteen eighty nine"、"one thousand nine hundred and eighty nine" 等英文敘述轉為整數 232、1989、1989。
import re
_KNOWN = {
'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4,
'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9,
'ten': 10, 'eleven': 11, 'twelve': 12, 'thirteen': 13,
'fourteen': 14, 'fifteen': 15, 'sixteen': 16, 'seventeen': 17,
'eighteen': 18, 'nineteen': 19, 'twenty': 20,
'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60,
'seventy': 70, 'eighty': 80, 'ninety': 90
}
def spoken_word_to_number(text: str) -> int:
text = text.lower().strip()
if text in _KNOWN:
return _KNOWN[text]
# 切分:空格或連字號
words = re.split(r'[ -]', text)
words = [w for w in words if w not in ('and', 'minus', 'negative')]
# 處理 hundred/thousand 結尾補零
if words[-1] == 'hundred':
words += ['zero', 'zero']
elif words[-1] == 'thousand':
words += ['zero', 'zero', 'zero']
if words[0] in ('hundred', 'thousand'):
words.insert(0, 'one')
output = 0
position = 'unit' # unit → ten → hundred → thousand
for word in reversed(words):
if position == 'unit':
num = _KNOWN[word]
output += num
position = 'hundred' if num > 9 else 'ten'
elif position == 'ten':
if word != 'hundred':
num = _KNOWN[word]
output += num * 10 if num < 10 else num
position = 'hundred'
elif position == 'hundred':
if word not in ('hundred', 'thousand'):
num = _KNOWN[word]
output += num * 100
position = 'thousand' if word == 'thousand' else 'hundred'
elif position == 'thousand':
if word != 'thousand':
num = _KNOWN[word]
output += num * 1000
# 千位以上不再處理 (可擴充 million)
return output
# 測試驗證
assert spoken_word_to_number("nine hundred") == 900
assert spoken_word_to_number("one hundred") == 100
assert spoken_word_to_number("eleven") == 11
assert spoken_word_to_number("twenty two") == 22
assert spoken_word_to_number("thirty-two") == 32
assert spoken_word_to_number("two hundred thirty two") == 232
assert spoken_word_to_number("nineteen hundred eighty nine") == 1989
assert spoken_word_to_number("one thousand nine hundred and eighty nine") == 1989
assert spoken_word_to_number("nine thousand nine hundred") == 9900
print("All tests passed!")
_SCALES = [
(10**3, 'thousand'),
(10**6, 'million'),
(10**9, 'billion'),
(10**12, 'trillion'),
]
def parse_large_number(words):
# 依 scale 由大到小切分
total = 0
current = 0
for word in words:
if word in _KNOWN:
current += _KNOWN[word]
elif word == 'hundred':
current *= 100
else: # thousand, million...
scale_val = next(v for v, n in _SCALES if n == word)
total += current * scale_val
current = 0
return total + current
pip install word2number,from word2number import w2n; w2n.word_to_num("two million three thousand")