0

我有一段文字(如果有任何相关性,则是一篇报纸文章)想知道是否有一种方法可以提取包含 Objective-c 中特定关键字的所有句子?我一直在看 ParseKit,但运气不佳!

4

2 回答 2

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);
}

最后,您将获得一系列句子,其中都包含您要查找的文本。

于 2013-01-31T12:25:15.717 回答
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];
    }
}
于 2013-01-31T12:32:12.713 回答