将拼写的数字转换为数字 [英] Convert spelled out number to number

查看:135
本文介绍了将拼写的数字转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C / Cocoa中,有没有办法将拼写出来的单词转换为多种语言的 NSNumber 或同等语言?

Is there a way, in Objective-C/Cocoa, to convert spelled out words to an NSNumber or equivalent in multiple languages?

例如:

三个转换为 code>或将 ocho 转换为 8 (西班牙语)。

convert three to 3 or convert ocho to 8 (Spanish).

也略有不同,但 3 1/2 3.5

我可以编写我自己的代码来做到这一点,但我希望有一个内置的方法来做到这一点。

I could write my own code to do this, but I was hoping there was a built-in way to do this. Getting the translations of every number in several languages is something I'd like to avoid.

推荐答案

NSNumberFormatter 可以从文本转换为数字:

NSNumberFormatter can convert from text to numbers:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterSpellOutStyle;

NSLog(@"%@", [formatter numberFromString:@"thirty-four"]);
NSLog(@"%@", [formatter numberFromString:@"three point five"]);

formatter.locale = [[NSLocale alloc]initWithLocaleIdentifier:[NSLocale localeIdentifierFromComponents:@{NSLocaleLanguageCode: @"es"}]];

NSLog(@"%@", [formatter numberFromString:@"ocho"]);

它可以处理的问题有严重的限制(它不会自动检测语言,如果你偏离预期格式(例如,三十四而不是三十四),分数等),但对于窄域,它似乎做这项工作。

There are serious limitations as to what it can handle (it doesn't auto detect languages, if you deviate from the expected format (e.g. "thirty four" instead of "thirty-four"), fractions, etc.), but for the narrow domain, it appears to do the job.

这篇关于将拼写的数字转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆