Is there a way to convert number words to Integers?

前端 未结 16 1984
北恋
北恋 2020-11-22 06:14

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

16条回答
  •  抹茶落季
    2020-11-22 07:03

    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).

提交回复
热议问题