Tuesday, 9 December 2014

String Extension Method (GetWordCounts): How to count the number of words in a string


Introduction

It's been a while since I've posted, but due to the apparent lack of buzz, I doubt you've missed me, if indeed, you are there.

However, I've had a little fun with strings which I feel is a small enough topic to quickly churn out into a post.


I am going to share an extension method I have written for the string type which allows you to count the number of occurrences of each word within a string. This can be especially handy if you feel slightly paranoid that you use certain words too often (#SoftwareForSelfImprovement).

An example...

We have the following string:

"Hello, how are you today? Are you well? Hello?"

And we want to return a dictionary that contains the following:

Word    Count
hello     2
how      1
are        2
you       2
today    1
well      1

Below outlines how the code will work in practice:

 1. Lowering all the characters to lower case:

"hello, how are you today? are you well? hello?"

2. Stripping out the special characters:

"hello how are you today are you well hello"

3. Splitting this into an array of words:

["hello", "how", "are", "you", "today", "are", "you", "well", "hello"]

4. Then finally looping through each word, adding it to the dictionary but if it already exists then increasing the counter on the value instead.

This article will attempt to express my approach here by first explaining the method I have written and the arguments available and then finally explaining each step of the code.

I have also added my unit tests at the end of this post, to show you some more examples and the test cases that I used to prove this code works.

Why an Extension Method?

You may be wondering why I have chosen to use an extension method.

Normally, I am apprehensive of using extension methods, I feel that it should only be used if the method is generic enough to handle any value of that type. And in this case, I feel this method has the ability to be used on any string that is given and so it really is an extension to the string type.

String.GetWordCounts

Dictionary<string, int> GetWordCounts(this string text, bool ignoreCase = false, char[] invalidCharacters = null)

text is the string that contains the words you wish to count.

ignoreCase is the option to ignore the case of the characters when determining if the word is the same or not. For example, the words "Word" and "word" might want to be considered as being the same.

invalidCharacters is a char array which contains special characters we want to exclude from the calculation. e.g. the words "word!" and "word" might want to be considered as being the same. However, special characters within the string will not be excluded. For example, "they're" and "theyre"

The return type is Dictionary<string, int>: The key represents a unique word and the value represents the number of times it occurs, as shown earlier in the introduction.

Code Logic

Below are the following steps
1. Formatting the text
2. Splitting the text
3. Populating the result dictionary

Formatting the text

The first step is to format the text, so that it is first in a suitable form for reliably extracting words.

The code begins by checking the optional parameters and performing the appropriate manipulations:

            if (!ignoreCase)
            {
                text = text.ToLower();
            }

            if (invalidCharacters != null)
            {
                text = text.RemoveSpecialCharacters(_invalidCharacters);
            }

If ignoreCase is set to false then we want to change the whole string to lower case. This is simply achieved by calling ToLower() on the string object.

The reason for this option is so we can group the same word despite it's case. For example, "FOO" and "foo" will be counted as one word.

Also, if we want to exclude special characters then an optional parameter
invalidCharacters can be populated. I have created another extension method which accepts the char array of characters we wish to exclude. For example, characters such as (" . ? !) will be removed from the string, but only if they occur on the outer sides of the word. Please read this post for an explanation of this.

Splitting the string

var splitChar = new char[] {' '};
var splitText = text.Split(splitChar, StringSplitOptions.None);

Next we use string.Split to split our string into an array of words. Here, a word is defined as a sequence of characters between two spaces. For example, " hello "

This array of words allows us to loop over each word for validating it for entry into our result dictionary.

Populating the result dictionary

The final stage is to create our result dictionary using our array of words.

As we loop through each word in the array, we check if the word is the last word in the text. If it isn't then we add a space after the word. This is so that we can check if the word is truly a word within the string. The last word in the string will not have a space after the word. We then add the word to the dictionary with a value of 1. However, if the word already exists as a key in the dictionary then we increment it's value. Finally, we remove this word from the string.

 private static Dictionary<string, int> CreateResultDictionary(string text)
        {
            Dictionary<string, int> resultDictionary = new Dictionary<string, int>();

            var splitChar = new char[] { ' ' };
            var splitText = text.Split(splitChar, StringSplitOptions.None);

            // For each word, add to dictionary. If it already exists then increment counter.
            for (int i = 0; i < splitText.Length; i++)
            {
                var word = splitText[i];

                if (!string.IsNullOrEmpty(word))
                {
                    // Check if this is the last word and format appropriately.
                    var formattedWord = i != splitText.Length - 1 ? word + " " : word;

                    if (text.Contains(formattedWord))
                    {
                        if (resultDictionary.ContainsKey(word))
                        {
                            resultDictionary[word]++;
                        }
                        else
                        {
                            resultDictionary.Add(word, 1);
                        }

                        text = text.Remove(text.IndexOf(formattedWord), formattedWord.Length);
                    }

                }
            }

            return resultDictionary;
        } 

I hope you found this interesting and please don't be shy, if you have any suggestions, I would love to hear them.

Take care.

Here is the full code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WordCount
{
    public static class StringExtension
    {
        public static Dictionary<string, int> GetWordCounts(this string text, bool ignoreCase = false, char[] invalidCharacters = null)
        {            

            if (!ignoreCase)
            {
                text = text.ToLower();
            }

            if (invalidCharacters != null)
            {
                text = text.RemoveSpecialCharacters(invalidCharacters);
            }

            return CreateResultDictionary(text);
        }

        private static Dictionary<string, int> CreateResultDictionary(string text)
        {
            Dictionary<string, int> resultDictionary = new Dictionary<string, int>();

            var splitChar = new char[] { ' ' };
            var splitText = text.Split(splitChar, StringSplitOptions.None);

            // For each word, add to dictionary. If it already exists then increment counter.
            for (int i = 0; i < splitText.Length; i++)
            {
                var word = splitText[i];

                if (!string.IsNullOrEmpty(word))
                {
                    // Check if this is the last word and format appropriately.
                    var formattedWord = i != splitText.Length - 1 ? word + " " : word;

                    if (text.Contains(formattedWord))
                    {
                        if (resultDictionary.ContainsKey(word))
                        {
                            resultDictionary[word]++;
                        }
                        else
                        {
                            resultDictionary.Add(word, 1);
                        }

                        text = text.Remove(text.IndexOf(formattedWord), formattedWord.Length);
                    }

                }
            }

            return resultDictionary;
        }        

        public static string RemoveSpecialCharacters(this string text, char[] invalidCharacters)
        {
            foreach (var c in invalidCharacters)
            {
                var charIndex = text.IndexOf(c);

                // If the characters index is at the end of the string.
                if (charIndex != -1 && charIndex + 1 == text.Length)
                {
                    text = text.Remove(text.IndexOf(c), 1);                    
                }
                else
                {
                    // Remove charcaters only if they are next to a space. (e.g. " 'Hello' ")
                    while (charIndex != -1 &&
                           (text.Substring(charIndex - 1, 1).Equals(" ") ||
                            text.Substring(charIndex + 1, 1).Equals(" ")))
                    {
                        text = text.Remove(text.IndexOf(c), 1);
                        charIndex = text.IndexOf(c);

                        // If the last character it finds is at the end of the string
                        if (charIndex != -1 && charIndex + 1 == text.Length)
                        {
                            text = text.Remove(text.IndexOf(c), 1);                            
                        }
                    }
                }
            }

            return text;
        }

    }
}


Unit Tests

       [TestMethod]
        public void Test_WordCounter_GetWordCounts_1()
        {
            Dictionary<string, int> resultWords = new Dictionary<string, int>()
            {
                {"ministers",1},
                {"of", 1},
                {"god", 1},
                {"were", 1},
                {"they", 1},
                {"wafting", 1},
                {"on", 1},
                {"their", 1},
                {"airy", 1},
                {"way", 1},
                {"food", 1},
                {"his", 2},
                {"servant's", 1},
                {"life", 1},
                {"to", 1},
                {"stay", 1},
                {"in", 1},
                {"drear", 1},
                {"retreat", 1},
            };

            string test = "Ministers of God were they, " +
                          "Wafting on their airy way " +
                          "Food his servant's life to stay " +
                          "In his drear retreat ;";
            
            Dictionary<string, int> words = test.GetWordCounts(false, new char[] { '.', ',', '!', '?', '\'', '"', ';' });            

            CollectionAssert.AreEquivalent(resultWords, words);
        }

        [TestMethod]
        public void Test_WordCounter_GetWordCounts_2()
        {
            Dictionary<string, int> resultWords = new Dictionary<string, int>()
            {
                {"the",4},
                {"moon", 1},
                {"is", 2},
                {"shining", 1},
                {"o'er", 1},                
                {"field", 1},
                {"a", 1},
                {"little", 1},
                {"breeze", 1},
                {"blowing", 1},
                {"radish", 1},
                {"leaves", 1},
                {"are", 2},
                {"crisp", 1},
                {"and", 1},
                {"green", 1},
                {"lettuces", 1},                
                {"growing", 1}
            };

            string test = "THE moon is shining o'er the field, " +
                            "A little breeze is blowing, " +
                            "The radish leaves are crisp and green, " +
                            "The lettuces are growing.";

            Dictionary<string, int> words = test.GetWordCounts(false, new char[] { '.', ',', '!', '?', '\'', '"', ';' }); 

            CollectionAssert.AreEquivalent(resultWords, words);
        }

        [TestMethod]
        public void Test_WordCounter_GetWordCounts_3()
        {
            Dictionary<string, int> resultWords = new Dictionary<string, int>()
            {
                {"a",2},
                {"b",1},
                {"c",3},
                {"d",1},
                {"e",1}              
            };

            string test = "a b c d e a c c";

            Dictionary<string, int> words = test.GetWordCounts(false, new char[] { '.', ',', '!', '?', '\'', '"', ';' }); 

            CollectionAssert.AreEquivalent(resultWords, words);
        }

        [TestMethod]
        public void Test_WordCounter_GetWordCounts_4()
        {
            Dictionary<string, int> resultWords = new Dictionary<string, int>()
            {
                {"a",3},
                {"b",3}                                
            };

            string test = "a a A b b B";

            Dictionary<string, int> words = test.GetWordCounts(false, new char[] { '.', ',', '!', '?', '\'', '"', ';' }); 

            CollectionAssert.AreEquivalent(resultWords, words);
        }

        [TestMethod]
        public void Test_WordCounter_GetWordCounts_5()
        {
            Dictionary<string, int> resultWords = new Dictionary<string, int>()
            {
                {"the",3},
                {"day",1},
                {"was",2}, 
                {"hot",1},
                {"a",2},
                {"cow",1},
                {"sat",1},
                {"by",1},
                {"and",1},
                {"in",2},
                {"her",1},
                {"ear",2},                
                {"big",1},
                {"fly",2},
                {"buz",4},
                {"did",1},
                {"go",1},
                {"cow's",1},                
                {"bit",1},
                {"it",1},
                {"so",1},
            };

            string test = "The day was hot " +
                            "A cow sat by, " +
                            "And in her ear " +
                            "Was a big fly. " +
                            "\"Buz, buz, buz, buz\" " +
                            "The fly did go, " +
                            "In the cow's ear, " +
                            "bit it so. ";

            Dictionary<string, int> words = test.GetWordCounts(false, new char[] { '.', ',', '!', '?', '\'', '"', ';' }); 

            CollectionAssert.AreEquivalent(resultWords, words);
        }

No comments:

Post a Comment