RingDotNetfor Ring

A spell checker

How does a program know that "brwn" probably means "brown"? This lesson keeps a dictionary in a set, measures how different two words are with the edit distance, and suggests the closest words.

What you will learn#

The program#

samples/UsingDotNet/tutorials/ch02_spelling.ring
# a spell checker - a set of words, edit distance (Levenshtein) and the best suggestions
load "dotnet.ring"

using {
	"System.Collections.Generic"
	"System.Text.RegularExpressions"
}

aDictionary = ["the","quick","brown","fox","jumps","over","lazy","dog","and","then","there","their","brain","crown","frown","jump","quack","quiet","lake","dig","dot","dug"]

func main

	# 1. A StringSet (a .NET HashSet) answers "is this word known?" at once, however many words it holds
	oWords = new StringSet()
	for cWord in aDictionary
		oWords.Add(cWord)
	next
	? "1. the dictionary has " + oWords.Count + " words. Contains 'fox'? " + yesNo(oWords.Contains("fox")) + ", 'fax'? " + yesNo(oWords.Contains("fax"))

	# 2. Edit distance: the least number of single-letter changes (insert, delete, replace) that turn one word into the other
	? nl + "2. distance(kitten, sitting) = " + distance("kitten","sitting") + "   (k->s, e->i, add g)"
	? "   distance(fox, fox) = " + distance("fox","fox") + ", distance(teh, the) = " + distance("teh","the") + ", distance(brwn, brown) = " + distance("brwn","brown")

	# 3. Suggestions: the dictionary words with the smallest distance to a word that is not known
	? nl + "3. suggestions for 'brwn'  : " + joinWith(suggest("brwn",3),", ")
	? "   suggestions for 'quik'  : " + joinWith(suggest("quik",3),", ")
	? "   suggestions for 'jumsp' : " + joinWith(suggest("jumsp",3),", ")

	# 4. Check a whole text: find the words with a regular expression, keep the position, mark what is unknown
	cText = "Teh quick brwn fox jumps ovr the lazy dgo"
	? nl + "4. checking: " + cText
	oMatches = new Regex("[A-Za-z]+").Matches(cText)
	nMistakes = 0
	for nIndex = 0 to oMatches.Count - 1
		cWord = lower(oMatches.Item(nIndex).Value)
		if not oWords.Contains(cWord)
			nMistakes++
			? "   '" + oMatches.Item(nIndex).Value + "' at position " + (oMatches.Item(nIndex).Index + 1) + " -> " + joinWith(suggest(cWord,2),", ")
		ok
	next
	? "   " + nMistakes + " words to check"

# The distance with a table: aTable[i][j] = the distance between the first i letters of cA and the first j letters of cB.
# The first row and column are the distances to the empty text. Each cell is the cheapest of: delete, insert, replace (free when the letters are equal).
func distance cA, cB

	nA = len(cA)
	nB = len(cB)
	aTable = []
	for nI = 0 to nA
		aRow = []
		for nJ = 0 to nB
			aRow + 0
		next
		aTable + aRow
	next
	for nI = 0 to nA
		aTable[nI + 1][1] = nI
	next
	for nJ = 0 to nB
		aTable[1][nJ + 1] = nJ
	next
	for nI = 1 to nA
		for nJ = 1 to nB
			nCost = 1
			if substr(cA,nI,1) = substr(cB,nJ,1)
				nCost = 0
			ok
			nDelete = aTable[nI][nJ + 1] + 1
			nInsert = aTable[nI + 1][nJ] + 1
			nReplace = aTable[nI][nJ] + nCost
			aTable[nI + 1][nJ + 1] = min(nDelete,min(nInsert,nReplace))
		next
	next
	return aTable[nA + 1][nB + 1]

# the nCount closest dictionary words: sorted by distance, equal distances alphabetically
func suggest cWord, nCount

	aScored = []
	for cKnown in aDictionary
		aScored + [distance(cWord,cKnown),cKnown]
	next
	for nI = 1 to len(aScored) - 1
		for nJ = nI + 1 to len(aScored)
			if aScored[nJ][1] < aScored[nI][1] or (aScored[nJ][1] = aScored[nI][1] and strcmp(aScored[nJ][2],aScored[nI][2]) < 0)
				aTemp = aScored[nI]
				aScored[nI] = aScored[nJ]
				aScored[nJ] = aTemp
			ok
		next
	next
	aBest = []
	for nI = 1 to min(nCount,len(aScored))
		aBest + aScored[nI][2]
	next
	return aBest

func joinWith aList, cSeparator

	cText = ""
	for cItem in aList
		if cText != ""
			cText += cSeparator
		ok
		cText += cItem
	next
	return cText

func yesNo lValue

	if lValue
		return "yes"
	ok
	return "no"
Output
1. the dictionary has 22 words. Contains 'fox'? yes, 'fax'? no

2. distance(kitten, sitting) = 3   (k->s, e->i, add g)
   distance(fox, fox) = 0, distance(teh, the) = 2, distance(brwn, brown) = 1

3. suggestions for 'brwn'  : brown, brain, crown
   suggestions for 'quik'  : quick, quack, quiet
   suggestions for 'jumsp' : jump, jumps, dug

4. checking: Teh quick brwn fox jumps ovr the lazy dgo
   'Teh' at position 1 -> the, then
   'brwn' at position 11 -> brown, brain
   'ovr' at position 26 -> over, and
   'dgo' at position 39 -> dig, dog
   4 words to check

How it works#

The set#

A list answers "is this word in it?" by looking at the items one by one: ten times more words, ten times more work. A set (StringSet, a .NET HashSet) answers with Contains in about the same time however big it is. A real dictionary has hundreds of thousands of words, and a set is the right place for it (the tutorial Collections and LINQ).

The edit distance#

The edit distance between two words is the smallest number of single-letter changes — insert, delete or replace — that turn one into the other: kitten → sitting is 3 (k→s, e→i, add g). Words with a small distance are probably typing mistakes of each other.

The program computes it with a table. aTable[i][j] holds the distance between the first i letters of the first word and the first j letters of the second. The first row and column are easy (turning the empty word into j letters takes j insertions). Every other cell is the cheapest of three ways:

FromMeaningCost
the cell abovedelete a letter+1
the cell on the leftinsert a letter+1
the cell diagonallyreplace a letter+0 if the letters are equal, else +1

The corner at the end is the answer. Each cell is computed from three neighbors that are already known, so the work is length1 × length2 steps. This technique — fill a table so that nothing is computed twice — is the same idea as the cache in the tutorial Speed — measure first.

Suggestions#

suggest gives every dictionary word a score (its distance to the typed word), sorts by score and then alphabetically (strcmp), and returns the first few. brwn has distance 1 to brown and 2 to brain and crown.

Checking a text#

Regex.Matches("[A-Za-z]+") finds the words and, for each one, its Index, so the program can say where the mistake is. It converts the word to lower case, asks the set, and only for unknown words does the (more expensive) search for suggestions. Do the cheap test first.

Note

Plain edit distance counts a swap of two neighbor letters (teh for the) as 2 changes. The Damerau variant counts it as 1; it is a good exercise.

What you learned#

Exercises#

  1. Add the swap of neighbors (Damerau distance) and see teh → the become 1.
  2. Read the dictionary from a text file with one word per line.
  3. Print the checked text with [brackets] around the unknown words.
  4. Suggest only words that start with the same letter, and measure how much faster it is (the tutorial Speed — measure first).

Next#

A project: mail merge

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.