2012-03-29 78 views
1

有一個包含幾個文本文件的目錄。如何計算每個文件中每個單詞的頻率?一個字是指一組可以包含字母,數字和下劃線字符的字符。統計每個單詞的頻率

+1

你想做什麼?你是怎麼試圖做到的?它是如何工作的? – 2012-03-29 18:26:23

+0

我不知道我應該先做些什麼。主要問題是我如何搜索單詞?我應該使用什麼通用容器來存儲有關單詞,計數頻率和文件的信息。 – 2012-03-29 19:55:18

回答

5

這裏是一個解決方案,應該算在所有字的頻率file:

private void countWordsInFile(string file, Dictionary<string, int> words) 
    { 
     var content = File.ReadAllText(file); 

     var wordPattern = new Regex(@"\w+"); 

     foreach (Match match in wordPattern.Matches(content)) 
     { 
      int currentCount=0; 
      words.TryGetValue(match.Value, out currentCount); 

      currentCount++; 
      words[match.Value] = currentCount; 
     } 
    } 

您可以調用該代碼:

 var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase); 

     countWordsInFile("file1.txt", words); 

這句話後,將包含文件中的所有單詞,它們的頻率(例如words["test"]返回文件內容中「test」的次數。如果您需要累積多個文件的結果,只需使用同一個字典調用所有文件的方法即可。如果每個文件需要單獨的結果,那麼每次創建一個新的字典並使用像@DarkGray建議的結構。

1

字計數:

int WordCount(string text) 
{ 
    var regex = new System.Text.RegularExpressions.Regex(@"\w+"); 

    var matches = regex.Matches(text); 
    return matches.Count;  
} 
從文件

閱讀文本:

string text = File.ReadAllText(filename); 

字計數結構:

class FileWordInfo 
{ 
    public Dictionary<string, int> WordCounts = new Dictionary<string, int>(); 
} 

List<FileWordInfo> fileInfos = new List<FileWordInfo>(); 
+0

這個正則表達式是否允許一組字符只能包含字母,數字和下劃線字符?我應該使用哪種通用容器來存儲有關單詞,計數頻率和文件的信息? – 2012-03-30 05:20:50

+0

@Grienders檢查當前的變體 – 2012-03-30 14:27:35

+0

你的代碼是做什麼的?它不會做我需要的!它是計算每個單詞的頻率還是計算所有單詞的數量? – 2012-03-30 19:44:15

0

@aKzenT答案很好,但有問題!他的代碼從不檢查單詞是否已經存在於字典中!所以我修改了代碼如下:

private void countWordsInFile(string file, Dictionary<string, int> words) 
{ 
    var content = File.ReadAllText(file); 

    var wordPattern = new Regex(@"\w+"); 

    foreach (Match match in wordPattern.Matches(content)) 
    { 
     if (!words.ContainsKey(match.Value)) 
      words.Add(match.Value, 1); 
     else 
      words[match.Value]++; 
    } 
} 
3

有一個Linq-ish的替代品,它更簡單。這裏的關鍵是使用File.ReadLines(這是懶惰閱讀這是很酷)和string.Split內置的框架。

private Dictionary<string, int> GetWordFrequency(string file) 
{ 
    return File.ReadLines(file) 
       .SelectMany(x => x.Split()) 
       .Where(x => x != string.Empty) 
       .GroupBy(x => x) 
       .ToDictionary(x => x.Key, x => x.Count()); 
} 

要從多個文件中獲取頻率,您可以根據params有一個過載。

private Dictionary<string, int> GetWordFrequency(params string[] files) 
{ 
    return files.SelectMany(x => File.ReadLines(x)) 
       .SelectMany(x => x.Split()) 
       .Where(x => x != string.Empty) 
       .GroupBy(x => x) 
       .ToDictionary(x => x.Key, x => x.Count()); 
}