【问题标题】:How to convert amount in words to number如何将单词中的金额转换为数字
【发布时间】:2012-02-10 10:01:45
【问题描述】:

我正在寻找一个将单词中的数量转换为相对数字的 c# 函数。

例如,1025 应转换为 1025。

感谢任何人的早期帮助。

【问题讨论】:

标签: c# numbers word


【解决方案1】:

已经测试过它可以处理包含多个数字的字符串。

用法:findNumbers("The cost is five hundred twenty nine thousand three hundred and twenty six dollars and twenty three cents");

输出:“成本为 529326 美元和 23 美分”

    string numstring = "zero=0;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;fourty=40;fifty=50;sixty=60;seventy=70;eighty=80;ninety=90;hundred=100;thousand=1000;";
    Dictionary<string, string> theNumbers = numstring.TrimEnd(';').Split(';').ToDictionary(item => item.Split('=')[0], item => item.Split('=')[1]);
    private string findNumbers(string input)
    {
        string tmp = "", tmpout = "", output = "";
        input = input.Replace("hundred and", "hundred");
        foreach (string word in input.Split(' '))
        {
            if (theNumbers.TryGetValue(word, out tmp))
            {
                if (tmpout != "") tmpout += " ";
                tmpout += tmp;
            } else
            {
                if (tmpout != "") output += " " + addNumbers(tmpout);
                tmpout = "";
                if (output != "") output += " ";
                output += word;
            }
        }
        if (tmpout != "") {
            tmpout = addNumbers(tmpout);
            if (output != "") output += " ";
            output += tmpout;
        }
        return output;
    }
    private string addNumbers(string input)
    {
        int output = 0;
        int output2 = 0;
        foreach (string num in input.Split(' '))
        {
            if (output > 999)
            {
                output2 = output;
                output = 0;
            }
            if (Int32.Parse(num) > 99)
            {
                output = output * Int32.Parse(num);
            } else
            {
                output = output + Int32.Parse(num);
            }
        }
        return (output + output2).ToString();
    }

【讨论】:

  • 请注意,这不适用于诸如“五九”之类的字符串。结果应该是“5 9”,但实际结果是“14”。它还假设单词“and”只会出现在单词“hundred”之后,所以像“1005”这样的字符串会导致“1000 and 5”实际上应该是“1005”
【解决方案2】:

检查下面的链接,它是用 Python 编写的,但你可以看到它是否有用。

问候

Is there a way to convert number words to Integers?

【讨论】:

    【解决方案3】:

    Marc Burns 的 ruby gem 可以做到这一点。我最近分叉了它以增加多年的支持。您可以拨打ruby code from C#

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多