Is there a way to convert number words to Integers?

前端 未结 16 2266
北恋
北恋 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 06:59

    I took @recursive's logic and converted to Ruby. I've also hardcoded the lookup table so its not as cool but might help a newbie understand what is going on.

    WORDNUMS = {"zero"=> [1,0], "one"=> [1,1], "two"=> [1,2], "three"=> [1,3],
                "four"=> [1,4], "five"=> [1,5], "six"=> [1,6], "seven"=> [1,7], 
                "eight"=> [1,8], "nine"=> [1,9], "ten"=> [1,10], 
                "eleven"=> [1,11], "twelve"=> [1,12], "thirteen"=> [1,13], 
                "fourteen"=> [1,14], "fifteen"=> [1,15], "sixteen"=> [1,16], 
                "seventeen"=> [1,17], "eighteen"=> [1,18], "nineteen"=> [1,19], 
                "twenty"=> [1,20], "thirty" => [1,30], "forty" => [1,40], 
                "fifty" => [1,50], "sixty" => [1,60], "seventy" => [1,70], 
                "eighty" => [1,80], "ninety" => [1,90],
                "hundred" => [100,0], "thousand" => [1000,0], 
                "million" => [1000000, 0]}
    
    def text_2_int(string)
      numberWords = string.gsub('-', ' ').split(/ /) - %w{and}
      current = result = 0
      numberWords.each do |word|
        scale, increment = WORDNUMS[word]
        current = current * scale + increment
        if scale > 100
          result += current
          current = 0
        end
      end
      return result + current
    end
    

    I was looking to handle strings like two thousand one hundred and forty-six

提交回复
热议问题