2013-01-31 27 views
0

我有一個文本塊(如果它的任何相關性的報紙文章)不知道是否有一種方法可以提取包含在Objective-C的特定關鍵字的所有句子?我一直在看ParseKit,但沒有太多的運氣!提取句子的關鍵字目標C

回答

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

在最後你將有一個包含你正在尋找的文字句子所有的數組。

+0

我想大多數的問題是確定文章中的句子,而不是僅僅進行文本搜索。 – trojanfoe

+0

這將通過句子列舉給你。你不需要自己確定它們。塊功能然後用文本對每個句子進行搜索。因此「NSEnumerationBySentences」。 – Fogmeister

+0

你能解釋一下它怎麼做?我沒有看到代碼來尋找句號(一種常見的分隔句子的方式)。 – trojanfoe

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]; 
    } 
} 
+0

這是行不通的要麼 」!」等... – Fogmeister

+0

好點!當然,您可以將您比較的字符串更改爲「。」,但它仍不會將拼寫錯誤或格式錯誤作爲考慮因素。 –