I need to convert one
into 1
, two
into 2
and so on.
Is there a way to do this with a library or a class or anythi
A quick solution is to use the inflect.py to generate a dictionary for translation.
inflect.py has a number_to_words()
function, that will turn a number (e.g. 2
) to it's word form (e.g. 'two'
). Unfortunately, its reverse (which would allow you to avoid the translation dictionary route) isn't offered. All the same, you can use that function to build the translation dictionary:
>>> import inflect
>>> p = inflect.engine()
>>> word_to_number_mapping = {}
>>>
>>> for i in range(1, 100):
... word_form = p.number_to_words(i) # 1 -> 'one'
... word_to_number_mapping[word_form] = i
...
>>> print word_to_number_mapping['one']
1
>>> print word_to_number_mapping['eleven']
11
>>> print word_to_number_mapping['forty-three']
43
If you're willing to commit some time, it might be possible to examine inflect.py's inner-workings of the number_to_words()
function and build your own code to do this dynamically (I haven't tried to do this).