提取包含关键词objective c的句子

时间:2013-01-31 12:14:53

标签: objective-c macos cocoa keyword

我有一个文本块(一篇报纸文章,如果它有任何相关性)想知道是否有办法在objective-c中提取包含特定关键词的所有句子?我一直在寻找ParseKit,但没有太多运气!

2 个答案:

答案 0 :(得分:5)

您可以使用本地NSString方法枚举句子......

NSString *string = @"your text";

NSMutableArray *sentences = [NSMutableArray array];

[string enumerateSubstringsInRange:NSMakeRange(0, string.length) 
                           options:NSStringEnumerationBySentences 
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    //check that this sentence has the string you are looking for
    NSRange range = [substring rangeOfString:@"The text you are looking for"];

    if (range.location != NSNotFound) {
        [sentences addObject:substring];
    }
}];

for (NSString *sentence in sentences) {
    NSLog(@"%@", sentence);
}

最后,您将拥有一系列包含您正在寻找的文本的句子。

答案 1 :(得分:0)

编辑:正如评论中所指出的,我的解决方案存在一些继承弱点,因为它需要一个完美格式化的句子,其中句号+空格仅用于实际结束句子时...我会留在这里,因为它可能是人们可以用另一个(已知的)分隔符对文本进行排序。

这是实现目标的另一种方式:

NSString *wordYouAreLookingFor = @"happy";

NSArray *arrayOfSentences = [aString componentsSeparatedByString:@". "]; // get the single sentences
NSMutableArray *sentencesWithMatchingWord = [[NSMutableArray alloc] init];

for (NSString *singleSentence in arrayOfSentences) {
    NSInteger originalSize = [singleSentence length];
    NSString *possibleNewString = [singleSentence stringByReplacingOccurrencesOfString:wordYouAreLookingFor withString:@""];

    if (originalSize != [possibleNewString length]) {
        [sentencesWithMatchingWord addObject:singleSentence];
    }
}