ios - iOS NSLinguisticTagger在获取词干时始终返回null

标签 ios objective-c cocoa-touch nlp nslinguistictagger

我需要将关键字(词法形式)与文本匹配,并返回关键字是否匹配(就像搜索引擎一样)

例如

text: I want some apples
keyword: apple
result: matched
keyword: banana
result: not matched

这是我的方法,我总是为标记获取null
- (BOOL)matchKeywordWithText:(NSString *)text keyword:(NSString *)keyword {

    __block NSMutableArray *words = [NSMutableArray array];


    NSLinguisticTaggerOptions options = NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerOmitPunctuation | NSLinguisticTaggerJoinNames;
    NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes: [NSLinguisticTagger availableTagSchemesForLanguage:@"en"] options:options];
    tagger.string = text;
    [tagger enumerateTagsInRange:NSMakeRange(0, [text length]) scheme:NSLinguisticTagSchemeLemma options:options usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) {
        NSString *token = [text substringWithRange:tokenRange];

        //TODO: TAG IS ALWAYS NULL HERE
        NSLog(@"words are %@: %@", token, tag);

        if (tag.length > 0) {
            [words addObject:tag];
        }
    }];

    for (NSString *word in words) {
        if ([word isEqualToString:keyword]) {
            return YES;
        }
    }

    return NO;

}

最佳答案

以下代码有效:

NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc]
                              initWithTagSchemes:[NSArray arrayWithObjects:NSLinguisticTagSchemeNameTypeOrLexicalClass, NSLinguisticTagSchemeLemma, nil]
                              options:(NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerOmitPunctuation)];
NSString *text = @"i'm apples";
[tagger setString:text];
[tagger enumerateTagsInRange:NSMakeRange(0, [text length])
                      scheme:NSLinguisticTagSchemeNameTypeOrLexicalClass
                     options:(NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerOmitPunctuation)
                  usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) {
                      NSString *token = [text substringWithRange:tokenRange];

                      NSString *lemma = [tagger tagAtIndex:tokenRange.location scheme:NSLinguisticTagSchemeLemma tokenRange:NULL sentenceRange:NULL];
                      if (lemma == nil) {
                          lemma = token;
                      }

                      NSLog(@"%@, %@", token, lemma);
                  }];

关于ios - iOS NSLinguisticTagger在获取词干时始终返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22861257/

相关文章:

ios - 在编辑模式下使用自定义滑动操作时如何防止单元格缩进?

iphone - 另一个 UIViewController 中的 UIViewController 的新实例 : Why can't I set an instance variable?

ios - 如何从 NSDate 获得 1 小时的 future 时差

cocoa-touch - Interface Builder 是否使用 -init 方法来初始化 View Controller ?

ios - 将 View 按钮与代码链接起来

ios - 不同的 iPhone 模拟器尺寸会导致节点错位

ios - 如何在 CallKit 中使用 CXStartCallAction isVideo 属性和原生视频按钮?

ios - CF网络崩溃

iphone - 我如何为 gps 实现监听器?

iphone - 它仅适用于模拟器,但不适用于设备