我想计算文本文件中重复的单词,我编写了以下
代码
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字。这段代码有什么问题。任何人都可以帮助我。