How to Convert Numeric Words into Numbers using Python

Challenge

Using Python, we want to convert words to numbers. In this challenge, we will explore how to convert a string into an integer.

The strings simply represent the numbers in words.

Examples:

  • “one” => 1
  • “twenty” => 20
  • “two hundred forty-six” => 246
  • “seven hundred eighty-three thousand nine hundred and nineteen” => 783919

Additional Notes:

  • The minimum number is “zero” (inclusively)
  • The maximum number, which must be supported is 1 million (inclusively)
  • The “and” in e.g. “one hundred and twenty-four” is optional, in some cases it’s present and in others, it’s not
  • All tested numbers are valid, you don’t need to validate them

Test cases

Test.assert_equals(parse_int('one'), 1)
Test.assert_equals(parse_int('twenty'), 20)
Test.assert_equals(parse_int('two hundred forty-six'), 246)

The solution in Python

def parse_int(textnum, numwords={}):
    # create our default word-lists
    if not numwords:

      # singles
      units = [
        "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
        "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
        "sixteen", "seventeen", "eighteen", "nineteen",
      ]

      # tens
      tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]

      # larger scales
      scales = ["hundred", "thousand", "million", "billion", "trillion"]

      # divisors
      numwords["and"] = (1, 0)

      # perform our loops and start the swap
      for idx, word in enumerate(units):    numwords[word] = (1, idx)
      for idx, word in enumerate(tens):     numwords[word] = (1, idx * 10)
      for idx, word in enumerate(scales):   numwords[word] = (10 ** (idx * 3 or 2), 0)

    # primary loop
    current = result = 0
    # loop while splitting to break into individual words
    for word in textnum.replace("-"," ").split():
        # if problem then fail-safe
        if word not in numwords:
          raise Exception("Illegal word: " + word)

        # use the index by the multiplier
        scale, increment = numwords[word]
        current = current * scale + increment
        
        # if larger than 100 then push for a round 2
        if scale > 100:
            result += current
            current = 0

    # return the result plus the current
    return result + current
Tags:
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments