Reputation: 9
I need to find the word frequency of a text file using a dictionary, however I am having trouble creating the key and value for the dictionary.
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);
}
Upvotes: 0
Views: 1749
Reputation: 11889
You appear to be missing the part that splits the line into words.
You can do this with string.Split
. Then you need to iterate over the words within each line, and then add each word to the dictionary.
In pseudo code:
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
}
Upvotes: 1