2013-03-28 4 views
6

Objective-C/Cocoa에서 단어의 철자를 NSNumber 또는 이와 동등한 언어로 여러 언어로 변환 할 수 있습니까? 예를 들어철자가있는 번호를 숫자로 변환

:

변환 three3 또는 ocho8로 (스페인어)를 변환합니다.

또한

약간 다른,하지만 3 1/23.5

에 나는이 작업을 수행하는 내 자신의 코드를 작성할 수 있지만, 나는이 작업을 수행 할 수있는 기본 방법이 있었다 기대했다. 여러 언어로 된 모든 숫자의 번역을 얻는 것은 내가 피하고 싶은 것입니다.

+3

"자연 언어"와 "NSNumberFormatter"에 대한 문서 검색 –

+0

@JoshuaNozzi 발견 한 바로는 'NSNumberFormatter'는이 작업의 반대 작업 만 수행 할 수 있습니다. – edc1591

+0

키 "1"에 2, "2"에 2 등의 값을 갖는 NSDictionnary를 만들 수 있습니다. 하지만 각 번호를 하나씩 써야합니다. 실용적인 것은 아닙니다. – 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"]); 

가 (당신이 예상되는 형식에서 벗어나는 경우가 자동으로 언어를 감지하지 않습니다 처리 할 수있는에 심각한 제한이 있습니다 (예 : "서른네 "대신"서른 넷 "), 분수 등), 좁은 영역에서는 작업을 수행하는 것처럼 보입니다.

+1

굉장! 나는'NSNumberFormatter'가 이것을 할 수 있을지 전혀 몰랐습니다. 감사! – edc1591

+0

이 솔루션은 마법처럼 작동합니다. 그러나 [formatter numberFromString : @ "three point one"]이 제대로 작동하더라도 [formatter numberFromString : @ "three point eleven"]에 대해 왜 (null) 값을 얻을 수 있는지 설명 할 수 있습니까? – static0886

+0

btw [formatter numberFromString : @ "three one one"]에 대해 3.11을 얻지 만 [formatter numberFromString : @ "one one point three"]에 대해 101.3을 얻습니다. – 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); 
     }]; 
} 

이 언제, 어떻게 분수 해상도 같은 일을 식별하는 작업과 당신을 떠나지 않습니다.