2010-10-27 97 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

簡單算法:將字符串拆分爲單詞數組,迭代該數組,並將每個單詞的計數存儲在散列表中。完成後按計數排序。