C++ || How To Create A Simple Predictive Spell Checker Using C++

Print Friendly, PDF & Email

The following is a module with functions which demonstrates how to create a simple predictive spell checker using C++.

The module demonstrated on this page is an implementation based on the Norvig Spelling Corrector.


1. Overview

In its simplest form, this process works by first telling the spelling corrector the valid words in our language. This is called “training” the corrector. Once the corrector is trained to know the valid words in our language, it tries to choose the word that is the most likely spelling correction.

This process is done by choosing the candidate with the highest probability to show up in our language. For example, should “lates” be corrected to “late” or “latest” or “lattes” or …? This choice is determined by the word which has the highest probability to appear in our language, according to the training text we provide.

Traditionally, spell checkers look for four possible errors: a wrong letter (“wird”), also knows as alteration. An inserted letter (“woprd”), a deleted letter (“wrd”), or a pair of adjacent transposed letters (“wrod”). This process is used when generating probable spelling correction candidates.

The training text used in the example on this page can be downloaded here. This file consists of 80891 distinct words, which is used to train the spelling corrector.


2. Spell Check – Basic Usage

The example below demonstrates the use of the ‘SpellChecker‘ class to load the training file and correct the spelling of a word.


3. Spell Check – Unit Tests

The example below demonstrates the use of the ‘SpellChecker‘ class to load the training file and correct the spelling of a word.

In this example, words are added to a set to determine if the most likely spelling correction is returned by the spelling corrector. The first word in the set is the word to test against (some are spelled correctly, some incorrectly). The second word in the set is the expected result that should be returned by the spelling corrector.

If no spelling suggestion is found, an empty string is returned by the spelling corrector. This is true for one of the words in the test cases below. Even though the word is spelled correctly, it is not defined in our training text, and no correction can be found.


4. SpellChecker Class

The following is the SpellChecker Class. Include this in your project to start using!

The following is the header file ‘SpellChecker.h‘.

The following is the implementation file ‘SpellChecker.cpp‘.


5. More Examples

Below are more examples demonstrating the use of the ‘SpellChecker‘ class. Don’t forget to include the module when running the examples!

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Remember to include the training file.

Leave a Reply