2013-03-28 10 views
6

在Objective-C/Cocoa中,是否有一种方法可以将拼写出的单词转换为NSNumber或多种语言的等效语言?将拼出的数字转换为数字

例如:

转换three3或转换ocho8(西班牙语)。

也略有不同,但3 1/23.5

我可以写我自己的代码来做到这一点,但我一直希望有一个内置的方式做到这一点。以多种语言获取每个数字的翻译是我想避免的。

+3

考虑搜索“自然语言”和“NSNumberFormatter”文档 –

+0

@JoshuaNozzi从我发现,'NSNumberFormatter'只能做到与此相反。 – edc1591

+0

您可以创建一个NSDictionnary,其值为1的“one”键,2的“two”等等。但是你必须一个接一个地写下每个数字 - 不太实际。 – Moray

回答

12

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

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"]); 

有严重的局限性,以什么它可以处理(它不会自动检测语言,如果与预期偏离格式(如“34 “而不是”三十四“),分数等),但是对于狭窄的领域来说,它似乎是做这项工作的。

+1

太棒了!我不知道“NSNumberFormatter”可以做到这一点。谢谢! – edc1591

+0

这个解决方案像魔术一样工作。然而,你可以解释为什么我得到(空格)[formatter numberFromString:@“three point 11”],即使[formatter numberFromString:@“three point one”]工作正常吗? – static0886

+0

顺便说一句,我得到3.11 [formatter numberFromString:@“three point one one”]但我得到101.3 [formatter numberFromString:@“one one point three”] – static0886

2

NSLinguisticTagger将以多种语言标记您的号码。

NSArray * texts = @[@"It's 3 degrees outside", @"Ocho tacos", @"What is 3 1/2?", @"ocho"]; 
for (NSString * text in texts) 
{ 
    NSLinguisticTaggerOptions options = NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerJoinNames; 
    NSArray * tagSchemes = [NSLinguisticTagger availableTagSchemesForLanguage:@"en"]; 
    tagSchemes = [tagSchemes arrayByAddingObjectsFromArray:[NSLinguisticTagger availableTagSchemesForLanguage:@"es"]]; 

    NSLinguisticTagger * tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:tagSchemes 
                       options:options]; 
    [tagger setString:text]; 

    [tagger enumerateTagsInRange:NSMakeRange(0, [text length]) 
          scheme:NSLinguisticTagSchemeNameTypeOrLexicalClass 
         options:options 
         usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) 
     { 
      NSString *token = [text substringWithRange:tokenRange]; 
      NSLog(@"%@: %@", token, tag); 
     }]; 
} 

这不会离开你确定如何和何时做的事情一样分数分辨率的任务。