文字数字转整数:Python现有可用库咨询(支持0至百万)
Hey there! Awesome call looking for existing libraries instead of building a parser from scratch—Python's got you covered here, with solid tools that handle both English and Spanish written numbers right up to the million range you need.
Here are the go-to options:
1. 英文文字转数字:word2number
This is the most widely used library for English, and it handles numbers well beyond a million with ease. It takes care of spaces, hyphens, and common phrasing like "twenty two" or "one hundred and fifty".
- Install it via pip:
pip install word2number - Example usage:
from word2number import w2n # Convert English text to integer print(w2n.word_to_num('twenty two')) # Output: 22 print(w2n.word_to_num('one million')) # Output: 1000000 print(w2n.word_to_num('nine hundred ninety nine thousand nine hundred ninety nine')) # Output: 999999
2. 西班牙语文字转数字:spanish_word2num
For Spanish, this dedicated library is perfect—it supports all standard number phrasing (including regional variants like "un millón" vs "un millon" if needed) and covers your 0 to 1,000,000 range flawlessly.
- Install it via pip:
pip install spanish-word2num - Example usage:
from spanish_word2num import spanish_to_num # Convert Spanish text to integer print(spanish_to_num('veintidós')) # Output: 22 print(spanish_to_num('un millón')) # Output: 1000000 print(spanish_to_num('doscientos treinta y cuatro mil quinientos sesenta y siete')) # Output: 234567
Bonus: Dual-language wrapper
If you need to handle both languages in one function, you can throw together a simple wrapper to switch between the two libraries:
from word2number import w2n from spanish_word2num import spanish_to_num def text_to_num(text, language='english'): if language.lower() == 'english': return w2n.word_to_num(text) elif language.lower() == 'spanish': return spanish_to_num(text) else: raise ValueError("Unsupported language. Choose 'english' or 'spanish'.") # Test it out print(text_to_num('twenty two', 'english')) # 22 print(text_to_num('veintidós', 'spanish')) # 22
All these libraries handle the grammar rules and edge cases (like hyphenated numbers, compound phrases) out of the box, so you don't have to mess with writing a custom parser or formal grammar.
内容的提问来源于stack exchange,提问作者DGoiko

