Count Words and Occurrences of Each Word in a Document using C#
Tags: csharp, dotnet, webdev
Published: 2019-10-18 06:23:05

Repetition of data can diminish the worth of the content. Working as a writer, you must follow [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) (don’t repeat yourself) principle. The statistics such as **word count** or the number of occurrences of each word can let you analyze the content but it’s hard to do it manually for multiple documents. So in this article, I’ll demonstrate how to **programmatically count words** and the **number of** **occurrences** of each word in **PDF**, **Word**, **Excel**, **PowerPoint**, **Ebook**, **Markup**, and **Email document** formats using **C#**. For extracting text from documents, I’ll be using [**GroupDocs.Parser for .NET**](https://products.groupdocs.com/parser/net) which is a powerful **document parsing API**.

### Steps to count words and their occurrences in C#

**1.** Create a new project.

**2.** Install _GroupDocs.Parser for .NET_ using NuGet Package Manager.

**3.** Add the following namespaces.
```csharp
using GroupDocs.Parser;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq; 
```
**4.** Create an instance of the _[Parser](https://apireference.groupdocs.com/net/parser/groupdocs.parser/parser)_ class and load the document.
```csharp
using (Parser parser = new Parser("sample.pdf"))
{
  // your code goes here.
}
```
**5.** Extract the text from the document into a _[TextReader](https://docs.microsoft.com/en-us/dotnet/api/system.io.textreader?view=netframework-4.8)_ object using _[Parser.GetText()](https://apireference.groupdocs.com/net/parser/groupdocs.parser/parser/methods/gettext)_ method.
```csharp
using (TextReader reader = parser.GetText())
{

}
```
**6.** Split up the text into words, save them into a string array and perform word count.
```csharp
Dictionary<string, int> stats = new Dictionary<string, int>();
string text = reader.ReadToEnd();
char[] chars = { ' ', '.', ',', ';', ':', '?', '\n', '\r' };
// split words
string[] words = text.Split(chars);
int minWordLength = 2;// to count words having more than 2  characters

// iterate over the word collection to count occurrences
foreach (string word in words)
{
	string w = word.Trim().ToLower();
	if (w.Length > minWordLength)
	{
		if (!stats.ContainsKey(w))
		{
			// add new word to collection
			stats.Add(w, 1);
		}
		else
		{
			// update word occurrence count
			stats[w] += 1;
		}
	}
}
```
**7. **Order the words by their occurrence count and display the results.
```csharp
// order the list by word count
var orderedStats = stats.OrderByDescending(x => x.Value);
// print total word count
Console.WriteLine("Total word count: {0}", stats.Count);
// print occurrence of each word
foreach (var pair in orderedStats)
{
	Console.WriteLine("Total occurrences of {0}: {1}", pair.Key, pair.Value);
}
```
### Complete Code
```csharp
using (Parser parser = new Parser("sample.pdf"))
{                
	// Extract a text into the reader
	using (TextReader reader = parser.GetText())
	{
		Dictionary<string, int> stats = new Dictionary<string, int>();
		string text = reader.ReadToEnd();
		char[] chars = { ' ', '.', ',', ';', ':', '?', '\n', '\r' };
		// split words
		string[] words = text.Split(chars);
		int minWordLength = 2;// to count words having more than 2 characters

		// iterate over the word collection to count occurrences
		foreach (string word in words)
		{
			string w = word.Trim().ToLower();
			if (w.Length > minWordLength)
			{
				if (!stats.ContainsKey(w))
				{
					// add new word to collection
					stats.Add(w, 1);
				}
				else
				{
					// update word occurrence count
					stats[w] += 1;
				}
			}
		}

		// order the collection by word count
		var orderedStats = stats.OrderByDescending(x => x.Value);
		// print total word count
		Console.WriteLine("Total word count: {0}", stats.Count);
		// print occurrence of each word
		foreach (var pair in orderedStats)
		{
			Console.WriteLine("Total occurrences of {0}: {1}", pair.Key, pair.Value);
		}
	}
}
```
### Results
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/o1aupv49cd8rx6nwtr5i.png)