如何将数字的英文字符串转换为浮点数(例如"二十六" => 26.0)

时间:2015-12-01 23:53:33

标签: ruby algorithm nlp

我正在构建一个聊天机器人,我希望能够解析代表人类年龄的数字量的字符串。当我问"How old are you?"时,用户应该能够输入"26""twenty-six"并让机器人将其理解为26.0。该方法应处理将分数转换为小数。

示例:

parse("six")              # => 6.0
parse("twenty-five")      # => 25.0
parse("three and a half") # => 3.5

是否有一个gem已经在Ruby中处理过这个问题,或者写一个简单的parse方法是否容易?

1 个答案:

答案 0 :(得分:4)

这是一个只在输入字符串中查找数字并将它们添加到一起的解决方案。这适用于英语年龄< 100。

def parse(string)
  dict = {
    half: 0.5, one: 1, two: 2, three: 3, four: 4,
    five: 5, six: 6, seven: 7, eight: 8, nine: 9,
    ten: 10, eleven: 11, twelve: 12, thirteen: 13,
    fourteen: 14, fifteen: 15, sixteen: 16,
    seventeen: 17, eighteen: 18, nineteen: 19,
    twenty: 20, thirty: 30, forty: 40, fifty: 50,
    sixty: 60, seventy: 70, eighty: 80, ninety: 90
  }

  age = 0.0

  dict.each do |s, n|
    # Scans string for each number name, adding numeric value if found
    age += n if string[/\b#{s}\b/]
  end

  return age
end

parse "six"              # => 6.0
parse "twenty-five"      # => 25.0
parse "three and a half" # => 3.5
parse "four and twenty"  # => 24.0