2013-05-26 44 views
0

我要數在文本文件中重複的話,我寫了下面的代碼
代碼計數重複文本文件的話

private void button3_Click(object sender, EventArgs e) 
     { 
      string line; 
      using (StreamReader reader = new StreamReader("D:\\mun.txt")) 
      { 

       while ((line = reader.ReadLine()) != null) 
       { 
        richTextBox1.Text = reader.ToString(); 
       } 
      } 
      Regex regex = new Regex("\\w+"); 
      var frequencyList = regex.Matches(richTextBox1.Text) 
       .Cast<Match>() 
       .Select(c => c.Value.ToLowerInvariant()) 
       .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); 
      foreach (var item in frequencyList) 
      { 
       label1.Text =label1.Text+item.Word+"\n"; 
       label2.Text = label2.Text+item.Count.ToString()+"\n"; 
      } 
     }  

但是這個代碼給出錯誤的結果,此代碼只佔用了StreamReader一詞。這段代碼有什麼問題,有人幫助我。

+1

「有什麼不對這個代碼」 ---計算器是不是你的亂碼的在線調試器。 – zerkms

+0

'richTextBox1.AppendText(line);' – I4V

回答

2

如果你需要從文件中設置文本,你可以使用下面的ReadAllLines方法,當前代碼的問題是在while循環中每次迭代你代替richTextBox1文本。

richTextBox1.Lines =File.ReadAllLines("D:\\mun.txt") 
Regex regex = new Regex("\\w+"); 
var frequencyList = regex.Matches(richTextBox1.Text) 
    .Cast<Match>() 
    .Select(c => c.Value.ToLowerInvariant()) 
    .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); 
foreach (var item in frequencyList) 
{ 
    label1.Text =label1.Text+item.Word+"\n"; 
    label2.Text = label2.Text+item.Count.ToString()+"\n"; 
}