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

String Extension Method (RemoveSpecialCharacters)

Introduction

This post is an extension to a previous post about an extension method I had written for counting the number of times all words appear in the string.

For example, the word "extension" appeared twice in the sentence above.

If you haven't read it, then you will find it here

In this article, I would like to share the RemoveSpecialCharacters extension method.

String.RemoveSpecialCharacters

The purpose of this method is to strip out certain characters from a string. But only if they occur on the outside of what we consider to be a word.

For example, these words might appear in a string "Xmas!" and "Xmas". The subtle difference being that one word has an exclamation mark and the other hasn't, but they are both the same word. However, special characters within the word will not be excluded and so if we have the following words appearing in the string: "they're" and "theyre" then the method will not strip out the apostrophe because it is part of the word and so will consider these words to be different. (Even though the second word isn't really a word...)

Below is the signature:

public static string RemoveSpecialCharacters(this string text, char[] invalidCharacters)

text is the string we wish to perform this functionality on.

invalidCharacters are the characters we wish to exclude. For example:
new char[] { '.', ',', '!', '?', '\'', '"', ';' }
Firstly, we loop over each invalid character and find the index of it withing the string.
            foreach (var c in invalidCharacters)
            {
                var charIndex = text.IndexOf(c);

Now this is where it gets a little tricky.

Invalid characters may appear in a variety of ways within a string (and that is why unit tests are crucial to proving your logic works! I have included my unit tests at the bottom of this post). The text may appear like the following:

1. "a cat sat on the mat"
2. "a cat sat on the mat!"
3. "a, cat, sat, 'on' the, mat!"

The code is written to attempt to handle these three situations.

The first situation is covered as no specified special character appears in this string.
The second situation has only one special character and that appears at the end of the string with no spaces before or after this character.
The third situation has many special characters occuring throughout the string, plus the character at the end.

And remember, we don't want to exclude characters that occur within the word!

And now you understand these scenarios, let's continue onto the code.

Here, we have an initial check on the character index, we want to check that it exists within the string and also if it appears at the end of the string. If this is true, we remove it.
                if (charIndex != -1 && charIndex + 1 == text.Length)
                {
                    text = text.Remove(text.IndexOf(c), 1);                    
                }



However, if the character actually occurs somewhere within the string then we want to check if it is surrounded with a space either before or after it's index. For example, " word! " a space appears after the exclamation mark and so we wish to remove this. However, if this was the case " wor!d " then we won't remove it, as we must assume that the writer is young, hip and uses 1nt3rn37 5p34ch.

We use a while loop to ensure that we check all occurances of this character within the string and we remove the unwanted characters.

You may have spotted some duplicate code during this while loop (and yes, I am ashamed). After we remove the character, we then get the index of the next occurrence of this character and then we check  if it is the last character in the string and if so, we remove it. This is so that we can remove the last unwanted character within the string.

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

But as I'm aspiring to be a good developer and a decent human being, I will spend more time scratching my head over this as duplicate code always leaves a bitter taste. The issue here is that this condition occurs in the while loop that also occurs within the else block of the intial condition that we are duplicating (Does this make sense?). I am sure the fault is to do with the design of the code and perhaps changing the approach will sort this out, but let's see...

In the meantime, if this article remains unchanged, then I hope you have the brains to figure this out and would like to share it with me.

Take care.

Here is the full code:

 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_6()
        {
            Dictionary<string, int> resultWords = new Dictionary<string, int>()
            {
                {"a",1},
                {"cat",1},
                {"sat",1}, 
                {"on",1},
                {"the",1},
                {"mat",1},
            };

            string test = "a cat sat on the mat";

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

            CollectionAssert.AreEquivalent(resultWords, words);
        }

        [TestMethod]
        public void Test_WordCounter_GetWordCounts_7()
        {
            Dictionary<string, int> resultWords = new Dictionary<string, int>()
            {
                {"a",1},
                {"cat",1},
                {"sat",1}, 
                {"on",1},
                {"the",1},
                {"mat",1},
            };

            string test = "a cat sat on the mat!";

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

            CollectionAssert.AreEquivalent(resultWords, words);
        }

        [TestMethod]
        public void Test_WordCounter_GetWordCounts_8()
        {
            Dictionary<string, int> resultWords = new Dictionary<string, int>()
            {
                {"a",1},
                {"cat",1},
                {"sat",1}, 
                {"on",1},
                {"the",1},
                {"mat",1},
            };

            string test = "a, cat, sat, 'on' the, mat!";

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

            CollectionAssert.AreEquivalent(resultWords, words);
        }

Sunday, 19 January 2014

Simple Expanding Tree - JQuery and Divs


In this article I am going to show you how to build a simple tree expander using JQuery and HTML's Div tag. I have recently started experimenting with cshtml and JQuery in ASP.Net MVC4, so the solution I provide here may well not be the best, but it works and if you have any feedback then it will be great to hear from you.

Below is an example of what we want to achieve:














So that when clicking on a Year or a Month, a slow expanding animation will reveal nested items and thus will look super cool!

Below shows the code in my view that is responsible for the layout of the data in the tree expander:


@foreach(var item in Model)
{
    <div class="Year">
        @Html.DisplayTextFor(label => item.Name)
    </div>
    
    foreach(var month in item.ChildDates)
    {
        <div class="Month">
            &nbsp; @Html.DisplayTextFor(label => month.Name)
        </div>
        
        foreach (var blog in month.ChildDates)
        {
            <div class="Blog">
                &nbsp;&nbsp; <a>@Html.DisplayTextFor(label => blog.Name)</a>
            </div>
        }
    }
}

The model that I pass into the view is of type List<TreeViewLocation>.

I loop through each nested collection, displaying the name value of each TreeViewLocation and wrapping each displayed value in a Div that can help me identify it later on when we do some JQuery fun.

I believe the TreeViewLocation class originates from a MVC sample project, but I discovered it here:
http://forums.asp.net/p/1827387/5080740.aspx?MvcTreeView+from+Database+


  public class TreeViewLocation
    {
        public TreeViewLocation()
        {
            ChildLocation = new HashSet<TreeViewLocation>();
        }

        public int Id { get; set; }
        public string Name { get; set; }

        public virtual int? ParentLocationId { get; set; }

        public virtual ICollection<TreeViewLocation> ChildLocations { get; set; }
    }

As you can see the class is a recursive structure as it holds a collection of other TreeViewLocation's called ChildLocations. This provides us with a tree like structure which is what we need for our tree expander.

In our case, the root TreeViewLocation object represents a Year. The Year.ChildLocations property contains a nested collection of further TreeViewLocation's which represent each Month in that Year. Then Month.ChildLocations represents each Blog in that particular Month for that Year. Makes sense? Good...

Below shows the Javascript/JQuery functions used to create the tree expanding effect:

<script type="text/javascript">
    $(document).ready(function () {
        $('.Month').hide();
        $('.Blog').hide();
    });

    $(".Year").click(function () {
        $(this).nextUntil(".Year", ".Month").toggle("slow");
    });

    $(".Month").click(function () {
        $(this).nextUntil(".Month, .Year", ".Blog").toggle("slow");
    });

As the page is first loaded, I hide all the Month and Blog Divs - leaving only the Years displayed.

The Year and Month Div click events each use the nextUntil function. This help us identify which Divs we want to toggle. For example, when we click a Year, we want to toggle all Month Divs up until the next Year Div.

The toggle function allows us to show a Div if it is hidden and visa-versa.

And there you have it, a simple solution to implementing an animated tree expander. Happy climbing!