本文介绍了获取引词茎时,iOS NSLinguisticTagger始终返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to match a keyword (which is in its lexical form) with a text and return whether the keyword matches (just like a search engine)

例如

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

这是我的方法,标记始终为空

This is my method, I always get null for the tag

- (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 NSLinguisticTagger始终返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 04:09