[使用字典的C#词频

问题描述 投票:0回答:1

我需要使用字典来查找文本文件的单词频率,但是在创建字典的键和值时遇到了麻烦。我对编码还比较陌生,这是我对编程课的介绍的作业,如果这是一个愚蠢的问题,请抱歉。任何帮助表示赞赏!

        private void Form1_Load(object sender, EventArgs e)
    {
        StreamReader inputFile; //read the file 
        string words; //hold words from file
        int wordCount; //keep track of times words are repeated 

        //create dictionary 
        Dictionary<string, int> wordFrequency = new Dictionary<string, int>();

        //open file 
        inputFile = File.OpenText("Kennedy.txt");

        //read lines from file  
        while (!inputFile.EndOfStream)
        {
            words = inputFile.ReadLine();
            wordFrequency.Add(words, wordCount); //add elements to dictionary?

            //add words to list box
            lstboxwords.Items.Add(words); 
        }
c# dictionary
1个回答
0
投票

您似乎缺少将线分成单词的部分。

您可以使用string.Split执行此操作。然后,您需要遍历每一行中的单词,然后将每个单词添加到字典中。

使用伪代码:

line = inputFile.ReadLine(); // Read the whole line
words = line.Split(' '); // Split the line into words
foreach(var word in words)
{
   if(!wordFrequency.ContainsKey(word)) // Do we already know about this word?
   {  
       wordFrequency.Add(word, 0); // It's a new word
   }
   wordFrequency[word]++; // Increment the count for each word
}

此代码不完整,我们不应该做功课,因此有些事情需要修复。希望这能给您一些想法,让您陷于困境。

© www.soinside.com 2019 - 2024. All rights reserved.