12

给定一个字符串,我需要获取该字符串中出现的每个单词的计数。为此,我按单词将字符串提取到一个数组中,并以这种方式进行搜索,但我觉得直接搜索字符串更为理想。下面是我最初为解决问题而编写的代码。不过,我愿意就更好的解决方案提出建议。

NSMutableDictionary *sets = [[NSMutableDictionary alloc] init];

NSString *paragraph = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"text" ofType:@"txt"] encoding:NSUTF8StringEncoding error:NULL];

NSMutableArray *words = [[[paragraph lowercaseString] componentsSeparatedByString:@" "] mutableCopy];

while (words.count) {
    NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
    NSString *search = [words objectAtIndex:0];
    for (unsigned i = 0; i < words.count; i++) {
        if ([[words objectAtIndex:i] isEqualToString:search]) {
            [indexSet addIndex:i];
        }
    }
    [sets setObject:[NSNumber numberWithInt:indexSet.count] forKey:search];
    [words removeObjectsAtIndexes:indexSet];
}

NSLog(@"%@", sets);

例子:

起始字符串:
“这是一个测试。这只是一个测试。”

结果:

  • “这个” - 2
  • “是” - 2
  • “a2
  • “测试” - 2
  • “只有1个
4

3 回答 3

24

这正是 anNSCountedSet的用途。

您需要将字符串分成单词(iOS 很好地为我们提供了一个函数,这样我们就不必担心标点符号)并将它们中的每一个添加到计数集中,它会跟踪数字每个对象出现在集合中的次数:

NSString     *string     = @"This is a test. This is only a test.";
NSCountedSet *countedSet = [NSCountedSet new];

[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                           options:NSStringEnumerationByWords | NSStringEnumerationLocalized
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){

                            // This block is called once for each word in the string.
                            [countedSet addObject:substring];

                            // If you want to ignore case, so that "this" and "This" 
                            // are counted the same, use this line instead to convert
                            // each word to lowercase first:
                            // [countedSet addObject:[substring lowercaseString]];
                        }];

NSLog(@"%@", countedSet);

// Results:  2012-11-13 14:01:10.567 Testing App[35767:fb03] 
// <NSCountedSet: 0x885df70> (a [2], only [1], test [2], This [2], is [2])
于 2012-11-13T19:05:58.200 回答
2

如果我不得不猜测,我会这么说NSRegularExpression。像这样:

NSUInteger numberOfMatches = [regex numberOfMatchesInString:string
                                                    options:0
                                                      range:NSMakeRange(0, [string length])];

该片段取自此处


编辑 1.0:

根据蒂尔爵士所说:

NSString *string = @"This is a test, so it is a test";

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSArray *arrayOfWords = [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
for (NSString *word in arrayOfWords)
{
    if ([dictionary objectForKey:word])
    {
        NSNumber *numberOfOccurences = [dictionary objectForKey:word];
        NSNumber *increment = [NSNumber numberWithInt:(1 + [numberOfOccurences intValue])];
        [dictionary setValue:increment forKey:word];
    }
    else
    {
        [dictionary setValue:[NSNumber numberWithInt:1] forKey:word];
    }
}

你应该小心:

  • 标点符号。(接近其他词)
  • 大写单词与小写单词。
于 2012-11-13T18:23:17.153 回答
1

我认为您尝试使用循环在长段落中搜索单词真是个坏主意。你应该使用正则表达式来做到这一点!我知道第一次学习它并不容易,但它真的值得知道它!看看这个案例使用正则表达式查找/替换 NSString 中的子字符串

于 2012-11-13T18:36:08.917 回答