【发布时间】:2020-07-03 16:58:18
【问题描述】:
我想解析大量字符串以查找固定短语或名称,然后将名称(如果找到)存储在顺序重要的数组中。
例如,以字符串开头,例如:
str = "The movie stars Robert Duvall and James Earl Jones and pits them against a villain played expertly by Brando in an action packed adventure."
我想搜索一组演员:
names = [Robert Duvall, Henry Fonda, Brando, Marlon Brando, Jane Fonda, James Earl Jones, Peter Fonda, Montgomery Clift] 等,其中演员可以有一个、两个或三个名字。
最初,我可以使用strpos 简单地检查三元组是否匹配,或者将字符串转换为三元组,然后像 James Earl Jones 中那样对三元组进行匹配。然后我可以删除他的名字并在其余部分中搜索其他双打或单个单词。但是,这种方法很快就会变得非常复杂,我想知道是否没有更优雅的方法。
//这条路看起来确实很乱……
NSArray *triples = [self getTriples:str];//get all combinations of three sequential words
NSArray *pieces = [NSMutableArray new];
NSMutableArray * matches = [NSMutableArray new];
for (long i = 0;i<[triples count];i++) {
NSString *phrase = triples[i];
for (long j = 0;j<[names count];j++) {
NSString *name = names[j];
if ([phrase caseInsensitiveCompare:name]==NSOrderedSame) {
[matches addObject:phrase];
//Rumps has two elements, before and after
rumps = [str componentsSeparatedByString:phrase];
NSString *start = rumps[0];
NSString *end = rumps[1];
//Search before for a name
//search after for a name
}
}
}//end triples
感谢您的任何建议。
【问题讨论】:
-
字符串“Marlon Brando and Brando saw Brando and Marlon Brando”的预期结果是什么?
-
看看自然语言框架,它会在这个领域为你做很多工作。 developer.apple.com/documentation/naturallanguage/…
-
@pawello,预期的结果将是 [Marlon Brando],例如一个包含一个演员的数组,因此应该防止被骗。
-
那么 [Marlon Brando] 和 [Brando] 是两个不同的数组?
-
基本上我正在尝试搜索字符串并拉出提到的演员,以便按出现顺序获取演员数组。如果一个演员被提到两次,例如马龙白兰度和白兰度,那么在映射到演员之后,我可以使用类似 [[NSSet setWithArray:yourarray] allObjects];但是,我正在努力将字符串与可能使用的各种可能的演员名称进行比较。
标签: ios arrays objective-c swift strpos