【问题标题】:C# Word Frequency using Dictionary使用字典的 C# 词频
【发布时间】:2020-05-10 16:14:28
【问题描述】:

我需要使用字典查找文本文件的词频,但是我无法为字典创建键和值。

        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); 
        }

【问题讨论】:

  • 您可能需要在其中的某个地方将行拆分为单词。这些词需要与Dictionary 条目匹配,以便它们的计数可以更新或添加到Dictionary(如果它们是新词)。第一部分很难,例如处理标点符号,二是容易。 (“为什么是鸭子?”、“鸭子汤”、“鸭子!”、“鸭子、小袋鼠和雪貂走进酒吧……”有多少只鸭子?)

标签: c# dictionary


【解决方案1】:

您似乎缺少将行拆分为单词的部分。

您可以使用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
}

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2017-03-29
    • 1970-01-01
    • 2019-05-05
    • 2021-02-14
    • 1970-01-01
    • 2023-04-10
    • 2017-09-27
    • 1970-01-01
    相关资源
    最近更新 更多