numbers - 将单词转换为数字

标签 numbers language-agnostic

我在将单词转换为数字时遇到问题,例如

输入:

Five Thousand Six Hundred Thirty two

输出:

5632

我该怎么做?

最佳答案

在这里,我是用 python 做的,它会从算法的角度帮助你或其他人。

#!/usr/bin/python

__author__ = 'tomcat'

all = {
        "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,
        "hundred" : 100,
        "thousand" : 1000,
        "million" : 1000000,
        "billion" : 1000000000,
        "trillion" : 1000000000000,
        "quadrillion" : 1000000000000000,
        "quintillion" : 1000000000000000000,
        "sextillion" : 1000000000000000000000,
        "septillion" : 1000000000000000000000000,
        "octillion" : 1000000000000000000000000000,
        "nonillion" : 1000000000000000000000000000000
        };


spliter = {
        "thousand" : 1000,
        "million" : 1000000,
        "billion" : 1000000000,
        "trillion" : 1000000000000,
        "quadrillion" : 1000000000000000,
        "quintillion" : 1000000000000000000,
        "sextillion" : 1000000000000000000000,
        "septillion" : 1000000000000000000000000,
        "octillion" : 1000000000000000000000000000,
        "nonillion" : 1000000000000000000000000000000
        };

inputnumber = raw_input("Please enter string number : ");

tokens = inputnumber.split(" ");

result = 0;
partial_result = 0;
for index in range(len(tokens)):
    if tokens[index] in spliter :
        if partial_result == 0:
            partial_result = 1;
        partial_result *= all[tokens[index]];
        result += partial_result;
        partial_result = 0;
    else:
        if tokens[index] == "hundred" :
            if partial_result == 0:
                partial_result = 1;
            partial_result *= all[tokens[index]];

        else:
            partial_result += all[tokens[index]];


result += partial_result;

print result;

关于numbers - 将单词转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18548345/

相关文章:

algorithm - 为什么快速排序比归并排序好?

javascript - 如何检查用户输入的是不是数字?

actionscript-3 - 如何避免使用接口(interface)重用相同的实现代码?

algorithm - 检查一个单词是否由一个或多个串联的字典单词组成

haskell - Int 和 Integer 有什么区别?

language-agnostic - 当提到 'submitting a patch' 时,Patch 这个词究竟是什么意思?

c++ - 没有括号的 if 语句是否更快?

android - 获取EditTextValue并将其解析为整数部分只有一位的小数

c - 如何获取文件中的 float ?

paypal - WPS 中的 PayPal "amount"格式是什么?