2010-10-27 98 views
4

我需要计算每个关键字多少次重复发生在一个字符串,通过次数最多的排序。 用于此目的的.NET代码中可用的最快算法是什么?关键字.NET

+0

什么语言?我相信没有内置框架功能可以做到这一点,并且关于如何定义“关键字”的具体细节可能会使其变得复杂,例如,复数,标点符号等等。这是一个有趣的算法问题,但答案将取决于您使用的编程语言。 – 2010-10-27 16:47:58

+0

C#和VB.NET都可以接受。目前不需要排除不必要部分的能力,所有单词都很好。 – SharpAffair 2010-10-27 16:51:08

回答

6

编辑:下面的代码组,计

string[] target = src.Split(new char[] { ' ' }); 

var results = target.GroupBy(t => new 
{ 
    str = t, 
    count = target.Count(sub => sub.Equals(t)) 
}); 

这终于开始让我更有意义的独特记号......

编辑:下面的子目标相关的计数结果代码:

string src = "for each character in the string, take the rest of the " + 
    "string starting from that character " + 
    "as a substring; count it if it starts with the target string"; 
string[] target = {"string", "the", "in"}; 

var results = target.Select((t, index) => new {str = t, 
    count = src.Select((c, i) => src.Substring(i)). 
    Count(sub => sub.StartsWith(t))}); 

结果现在是:

+  [0] { str = "string", count = 4 } <Anonymous Type> 
+  [1] { str = "the", count = 4 } <Anonymous Type> 
+  [2] { str = "in", count = 6 } <Anonymous Type> 
下面

原始代码:

string src = "for each character in the string, take the rest of the " + 
    "string starting from that character " + 
    "as a substring; count it if it starts with the target string"; 
string[] target = {"string", "the", "in"}; 

var results = target.Select(t => src.Select((c, i) => src.Substring(i)). 
    Count(sub => sub.StartsWith(t))).OrderByDescending(t => t); 

与感激确认给this previous response。从调试

结果(这需要额外的逻辑包括匹配的字符串,其计数):

-  results {System.Linq.OrderedEnumerable<int,int>}  
-  Results View Expanding the Results View will enumerate the IEnumerable 
     [0] 6 int 
     [1] 4 int 
     [2] 4 int 
+0

现在这很酷。 – 2010-10-27 17:09:20

+0

是的,我需要回去和upvote我的来源。 – 2010-10-27 17:09:59

+0

我不知道它怎么会比蛮力方法来执行(例如只是遍历你正在寻找的关键字,使用的IndexOf找到事件,并指望他们收集器阵列)?我绝不意味着要从这个解决方案的可怕性中脱身,我只是好奇,因为我对linq的效率没有很好的理解。 – 2010-10-27 17:13:28

1

您可以将字符串分解为一个字符串集合,每个字符一个字符串,然后对该集合执行LINQ查询。虽然我怀疑它会是最快的,但它可能比正则表达式更快。

+0

在读取过程中检查单词/字符的出现之前,我已经实现了单通字符串读取器。您看到这种类型的代码功能用于CSV解析。 – wllmsaccnt 2010-10-27 16:52:39

4

说不上大约最快的,但LINQ的可能是最理解:

var myListOfKeywords = new [] {"struct", "public", ...}; 

var keywordCount = from keyword in myProgramText.Split(new []{" ","(", ...}) 
    group by keyword into g 
    where myListOfKeywords.Contains(g.Key) 
    select new {g.Key, g.Count()} 

foreach(var element in keywordCount) 
    Console.WriteLine(String.Format("Keyword: {0}, Count: {1}", element.Key, element.Count)); 

您可以在非LINQ的-Y方式写这篇文章,但基本前提是相同的;将字符串分成单词,并计算每个感兴趣单词的出现次数。

2

简单算法:将字符串拆分为单词数组,迭代该数组,并将每个单词的计数存储在散列表中。完成后按计数排序。