spellchecker

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 27, 2025 License: MIT Imports: 13 Imported by: 0

README

Spellchecker

Go Reference CI

Yet another spellchecker written in go.

Features:

  • very compact database: ~1 MB for 30,000 unique words
  • average time to fix a single word: ~35 µs
  • achieves about 70–74% accuracy on Peter Norvig’s test sets (see benchmarks)

Installation

go get -v github.com/f1monkey/spellchecker

Usage

Quick start

func main() {
	// Create a new instance
	sc, err := spellchecker.New(
		"abcdefghijklmnopqrstuvwxyz1234567890", // allowed symbols, other symbols will be ignored
		spellchecker.WithMaxErrors(2) 			// see options.go
	)
	if err != nil {
		panic(err)
	}

	// Load data from any io.Reader
	in, err := os.Open("data/sample.txt")
	if err != nil {
		panic(err)
	}
	sc.AddFrom(in)

	// Add words manually
	sc.Add("lock", "stock", "and", "two", "smoking", "barrels")

	// Check if a word is valid
	result := sc.IsCorrect("coffee")
	fmt.Println(result) // true

	// Correct a single word
	fixed, err := sc.Fix("awepon")
	if err != nil && !errors.Is(err, spellchecker.ErrUnknownWord) {
		panic(err)
	}
	fmt.Println(fixed) // weapon

	// Find up to 10 suggestions for a word
	matches, err := sc.Suggest("rang", 10)
	if err != nil && !errors.Is(err, spellchecker.ErrUnknownWord) {
		panic(err)
	}
	fmt.Println(matches) // [range, orange]
Options

See options.go for the list of available options.

Save/load
	sc, err := spellchecker.New("abc")

	// Save data to any io.Writer
	out, err := os.Create("data/out.bin")
	if err != nil {
		panic(err)
	}
	sc.Save(out)

	// Load data back from io.Reader
	in, err = os.Open("data/out.bin")
	if err != nil {
		panic(err)
	}
	sc, err = spellchecker.Load(in)
	if err != nil {
		panic(err)
	}
Custom score function

You can provide a custom scoring function if needed:

	var fn spellchecker.FilterFunc = func(src, candidate []rune, cnt int) (float64, bool) {
		// you can calculate Levenshtein distance here (see defaultFilterFunc in options.go for example)

		return 1.0, true // constant score
	}

	sc, err := spellchecker.New("abc", spellchecker.WithFilterFunc(fn))
	if err != nil {
		// handle err
	}

	// After loading a spellchecker from a file,
	// you need to set the function again:
	sc, err = spellchecker.Load(inFile)
	if err != nil {
		// handle err
	}

	err = sc.WithOpts(spellchecker.WithFilterFunc(fn))
	if err != nil {
		// handle err
	}

Benchmarks

Tests are based on data from Peter Norvig's article about spelling correction

Test set 1:
Running tool: /usr/bin/go test -benchmem -run=^$ -bench ^Benchmark_Norvig1$ github.com/f1monkey/spellchecker -count=1

goos: linux
goarch: amd64
pkg: github.com/f1monkey/spellchecker
cpu: 13th Gen Intel(R) Core(TM) i9-13980HX
Benchmark_Norvig1-32    	     348	   3385868 ns/op	        74.44 success_percent	       201.0 success_words	       270.0 total_words	  830803 B/op	   15504 allocs/op
PASS
ok  	github.com/f1monkey/spellchecker	3.723s
Test set 2:
Running tool: /usr/bin/go test -benchmem -run=^$ -bench ^Benchmark_Norvig2$ github.com/f1monkey/spellchecker -count=1

goos: linux
goarch: amd64
pkg: github.com/f1monkey/spellchecker
cpu: 13th Gen Intel(R) Core(TM) i9-13980HX
Benchmark_Norvig2-32    	     231	   4935406 ns/op	        71.25 success_percent	       285.0 success_words	       400.0 total_words	 1270755 B/op	   21801 allocs/op
PASS
ok  	github.com/f1monkey/spellchecker	4.057s

Documentation

Index

Constants

View Source
const DefaultAlphabet = "abcdefghijklmnopqrstuvwxyz"
View Source
const DefaultMaxErrors = 2

Variables

View Source
var ErrUnknownWord = fmt.Errorf("unknown word")

Functions

This section is empty.

Types

type FilterFunc added in v1.3.0

type FilterFunc func(src, candidate []rune, count uint) (float64, bool)

FilterFunc compares the source word with a candidate word. It returns the candidate's score and a boolean flag. If the flag is false, the candidate will be completely filtered out.

type Match added in v1.2.0

type Match struct {
	Value string
	Score float64
}

type OptionFunc

type OptionFunc func(s *Spellchecker) error

OptionFunc option setter

func WithFilterFunc added in v1.3.0

func WithFilterFunc(f FilterFunc) OptionFunc

WithFilterFunc set custom scoring function

func WithMaxErrors added in v0.1.0

func WithMaxErrors(maxErrors int) OptionFunc

WithMaxErrors sets maxErrors — the maximum allowed difference in bits between the "search word" and a "dictionary word". - deletion is a 1-bit change (proble → problem) - insertion is a 1-bit change (problemm → problem) - substitution is a 2-bit change (problam → problem) - transposition is a 0-bit change (problme → problem)

It is not recommended to set this value greater than 2, as it can significantly affect performance.

func WithScoreFunc deprecated added in v1.1.0

func WithScoreFunc(f ScoreFunc) OptionFunc

WithScoreFunc specify a function that will be used for scoring

Deprecated: use WithFilterFunc instead

func WithSplitter

func WithSplitter(f bufio.SplitFunc) OptionFunc

WithSplitter set splitter func for AddFrom() reader

type ScoreFunc deprecated added in v1.1.0

type ScoreFunc func(src []rune, candidate []rune, distance int, cnt uint) float64

ScoreFunc custom scoring function type

Deprecated: use FilterFunc instead

type Spellchecker

type Spellchecker struct {
	// contains filtered or unexported fields
}

func Load

func Load(reader io.Reader) (*Spellchecker, error)

Load reads spellchecker data from the provided reader and decodes it

func New

func New(alphabet string, opts ...OptionFunc) (*Spellchecker, error)

func (*Spellchecker) Add

func (m *Spellchecker) Add(words ...string)

Add adds provided words to the dictionary

func (*Spellchecker) AddFrom

func (m *Spellchecker) AddFrom(input io.Reader) error

AddFrom reads input, splits it with spellchecker splitter func and adds words to the dictionary

func (*Spellchecker) AddWeight added in v1.2.0

func (m *Spellchecker) AddWeight(weight uint, words ...string)

AddWeight adds provided words to the dictionary with a custom weight

func (*Spellchecker) Fix

func (s *Spellchecker) Fix(word string) (string, error)

func (*Spellchecker) IsCorrect

func (s *Spellchecker) IsCorrect(word string) bool

IsCorrect check if provided word is in the dictionary

func (*Spellchecker) Save

func (m *Spellchecker) Save(w io.Writer) error

Save encodes spellchecker data and writes it to the provided writer

func (*Spellchecker) Suggest

func (s *Spellchecker) Suggest(word string, n int) ([]string, error)

Suggest find top n suggestions for the word

func (*Spellchecker) SuggestScore added in v1.2.0

func (s *Spellchecker) SuggestScore(word string, n int) SuggestionResult

SuggestScore find top n suggestions for the word. Returns spellchecker scores along with words

func (*Spellchecker) WithOpts

func (s *Spellchecker) WithOpts(opts ...OptionFunc) error

WithOpt set spellchecker options

type SuggestionResult added in v1.2.0

type SuggestionResult struct {
	ExactMatch  bool
	Suggestions []Match
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL