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字。这段代码有什么问题。任何人都可以帮助我。

4

1 回答 1

2

如果你需要从文件中设置文本,你可以使用ReadAllLines下面的方法,当前代码的问题是在你替换richTextBox1文本的每次迭代中的 while 循环中。

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";
}
于 2013-05-26T11:56:50.763 回答