Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

ios - Detect Language of NSString

Somebody told me about a class for language recognition in Cocoa. Does anybody know which one it is?

This is not working:

NSSpellChecker *spellChecker = [NSSpellChecker sharedSpellChecker];
[spellChecker setAutomaticallyIdentifiesLanguages:YES];
NSString *spellCheckText = @"Guten Tag Herr Mustermann. Dies ist ein deutscher Text. Bitte l?schen Sie diesen nicht.";
[spellChecker checkSpellingOfString:spellCheckText startingAt:0];
NSLog(@"%@", [spellChecker language]);

The result is 'en' but should be 'de'.

question from:https://stackoverflow.com/questions/6325073/detect-language-of-nsstring

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is API in cocoa available to check the language of a string, and it is always best to use Foundation over CoreFoundation whenever possible.

NSArray *tagschemes = [NSArray arrayWithObjects:NSLinguisticTagSchemeLanguage, nil];
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:tagschemes options:0];
[tagger setString:@"Das ist ein bisschen deutscher Text. Bitte l?schen Sie diesen nicht."];
NSString *language = [tagger tagAtIndex:0 scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];

Alternatively, if you happen to have mixed language text, you can use the enumerateLinguisticTagsInRange API to get the language of each word in the text.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...