2010-12-23 68 views
1

我有一個文本文件存儲爲字符串變量。該文本文件被處理,以便它只包含小寫字和空格。現在,假設我有一個靜態詞典,它只是一個特定單詞列表,我想從文本文件中計算詞典中每個單詞的頻率。例如:計算文本文件中特定字的頻率

Text file: 

i love love vb development although i m a total newbie 

Dictionary: 

love, development, fire, stone 

我想看到的輸出如下所示,列出字典單詞和它的計數。如果它使編碼更簡單,它也只能列出出現在文本中的字典單詞。

=========== 

WORD, COUNT 

love, 2 

development, 1 

fire, 0 

stone, 0 

============ 

使用正則表達式(例如,「\ w +」),我可以得到所有的字比賽,但我不知道怎麼去說也都在字典中的計數,所以我堅持。效率至關重要,因爲字典非常大(約100,000字),文本文件也不小(每個約200kb)。

我很感激任何幫助。

Dictionary<string, int> count = 
    theString.Split(' ') 
    .GroupBy(s => s) 
    .ToDictionary(g => g.Key, g => g.Count()); 

現在你可以檢查是否存在於字典的話,並表示如果計數:

+0

也許像將字符串拆分成一個`Array`或`List`,然後迭代/處理列表? – 2010-12-23 17:08:52

+0

您已將此標籤標記爲c#和vb.net。這是什麼? – 2010-12-23 17:10:07

回答

5
var dict = new Dictionary<string, int>(); 

foreach (var word in file) 
    if (dict.ContainsKey(word)) 
    dict[word]++; 
    else 
    dict[word] = 1; 
6

您可以將它們分組,並把它變成一本字典數字符串中的單詞它確實如此。

0

使用Groovy的正則表達式facilty,我會如下做到這一點: -

def input=""" 
    i love love vb development although i m a total newbie 
""" 

def dictionary=["love", "development", "fire", "stone"] 


dictionary.each{ 
    def pattern= ~/${it}/ 
    match = input =~ pattern 
    println "${it}" + "-"+ match.count 
} 
0

試試這個。單詞變量顯然是你的文本字符串。關鍵字數組是您想要統計的關鍵字列表。

對於不在文本中的字典單詞,這不會返回0,但您指定此行爲可以。這應該會在滿足您的應用程序要求的同時爲您提供相對較好的性能。

string words = "i love love vb development although i m a total newbie"; 
string[] keywords = new[] { "love", "development", "fire", "stone" }; 

Regex regex = new Regex("\\w+"); 

var frequencyList = regex.Matches(words) 
    .Cast<Match>() 
    .Select(c => c.Value.ToLowerInvariant()) 
    .Where(c => keywords.Contains(c)) 
    .GroupBy(c => c) 
    .Select(g => new { Word = g.Key, Count = g.Count() }) 
    .OrderByDescending(g => g.Count) 
    .ThenBy(g => g.Word); 

//Convert to a dictionary 
Dictionary<string, int> dict = frequencyList.ToDictionary(d => d.Word, d => d.Count); 

//Or iterate through them as is 
foreach (var item in frequencyList) 
    Response.Write(String.Format("{0}, {1}", item.Word, item.Count)); 

如果你想達到同樣的事情,而無需使用正則表達式,因爲您已表示自己知道的一切是小寫用空格分開,你可以修改上面的代碼如下所示:

string words = "i love love vb development although i m a total newbie"; 
string[] keywords = new[] { "love", "development", "fire", "stone" }; 

var frequencyList = words.Split(' ') 
    .Select(c => c) 
    .Where(c => keywords.Contains(c)) 
    .GroupBy(c => c) 
    .Select(g => new { Word = g.Key, Count = g.Count() }) 
    .OrderByDescending(g => g.Count) 
    .ThenBy(g => g.Word); 

Dictionary<string, int> dict = frequencyList.ToDictionary(d => d.Word, d => d.Count);