knitr::opts_chunk$set(comment = "")
Hunspell is the spell checker library used by LibreOffice, OpenOffice, Mozilla Firefox, Google Chrome, Mac OS-X, InDesign, Opera, RStudio and many others. It provides a system for tokenizing, stemming and spelling in almost any language or alphabet. The R package exposes both the high-level spell-checker as well as low-level stemmers and tokenizers which analyze or extract individual words from various formats (text, html, xml, latex).
Hunspell uses a special dictionary format that defines which characters, words and conjugations are valid in a given language. The examples below use the (default)
"en_US" dictionary. However each function can be used in another language by setting a custom dictionary in the
dict parameter. See the section on dictionaries below.
Spell checking text consists of the following steps:
We can do each these steps manually or have Hunspell do them automatically.
hunspell_suggest functions can test individual words for correctness, and suggest similar (correct) words that look similar to the given (incorrect) word.
library(hunspell) # Check individual words words <- c("beer", "wiskey", "wine") correct <- hunspell_check(words) print(correct) # Find suggestions for incorrect words hunspell_suggest(words[!correct])
In practice we often want to spell check an entire document at once by searching for incorrect words. This is done using the
bad <- hunspell("spell checkers are not neccessairy for langauge ninjas") print(bad[]) hunspell_suggest(bad[])
Besides plain text,
hunspell supports various document formats, such as html or latex:
download.file("https://arxiv.org/e-print/1406.4806v1", "1406.4806v1.tar.gz", mode = "wb") untar("1406.4806v1.tar.gz", "content.tex") text <- readLines("content.tex", warn = FALSE) bad_words <- hunspell(text, format = "latex") sort(unique(unlist(bad_words)))
Use the text-extraction from the
pdftools package to spell check text from PDF files!
text <- pdftools::pdf_text('https://www.gnu.org/licenses/quick-guide-gplv3.pdf') bad_words <- hunspell(text) sort(unique(unlist(bad_words)))
spelling package builds on hunspell and has a wrapper to spell-check manual pages from R packages. Results might contain a lot of false positives for technical jargon, but you might also catch a typo or two. Point it to the root of your source package:
WORD FOUND IN ECMA V8.Rd:16, description:2,4 ECMAScript description:2 emscripten description:5 htmlwidgets JS.Rd:16 JSON V8.Rd:33,38,39,57,58,59,120 jsonlite V8.Rd:42 Ooms V8.Rd:41,120 Xie JS.Rd:26 Yihui JS.Rd:26
In order to lookup a word in a dictionary, hunspell needs to break it down in a stem (stemming) and conjugation affix. The
hunspell function does this automatically but we can also do it manually.
hunspell_stem looks up words from the dictionary which match the root of the given word. Note that the function returns a list because some words can have multiple matches.
# Stemming words <- c("love", "loving", "lovingly", "loved", "lover", "lovely") hunspell_stem(words)
hunspell_analyze function is similar, but it returns both the stem and the affix syntax of the word:
To support spell checking on documents, Hunspell includes parsers for various document formats, including text, html, xml, man or latex. The Hunspell package also exposes these tokenizers directly so they can be used for other application than spell checking.
text <- readLines("content.tex", warn = FALSE) allwords <- hunspell_parse(text, format = "latex") # Third line (title) only print(allwords[])
In text analysis we often want to summarize text via it's stems. For example we can count words for display in a wordcloud:
allwords <- hunspell_parse(janeaustenr::prideprejudice) stems <- unlist(hunspell_stem(unlist(allwords))) words <- sort(table(stems), decreasing = TRUE) print(head(words, 30))
Most of these are stop words. Let's filter these out:
df <- as.data.frame(words) df$stems <- as.character(df$stems) stops <- df$stems %in% stopwords::stopwords(source="stopwords-iso") wcdata <- head(df[!stops,], 150) print(wcdata, max = 40)
library(wordcloud2) names(wcdata) <- c("word", "freq") wcdata$freq <- (wcdata$freq)^(2/3) wordcloud2(wcdata)
Hunspell is based on MySpell and is backward-compatible with MySpell and aspell dictionaries. Chances are your dictionaries in your language are already available on your system!
A Hunspell dictionary consists of two files:
[lang].afffile specifies the affix syntax for the language
[lang].dicfile contains a wordlist formatted using syntax from the aff file.
Typically both files are located in the same directory and share the same filename, for example
list_dictionaries() function lists available dictionaries in the current directory and standard system paths where dictionaries are usually installed.
dictionary function is then used to load any of these available dictionaries:
If the files are not in one of the standard paths you can also specify the full path to either or both the dic and aff file:
dutch <- dictionary("~/workspace/Dictionaries/Dutch.dic") print(dutch)
<hunspell dictionary> affix: /Users/jeroen/workspace/Dictionaries/Dutch.aff dictionary: /Users/jeroen/workspace/Dictionaries/Dutch.dic encoding: UTF-8 wordchars: '-./0123456789\ĳ’
The hunspell R package includes dictionaries for
en_GB. So if you you don't speak
en_US you can always switch to the British English:
hunspell("My favourite colour to visualise is grey") hunspell("My favourite colour to visualise is grey", dict = 'en_GB')
If you want to use another language you need to make sure that the dictionary is available from your system. The
dictionary function is used to read in dictionary.
dutch <- dictionary("~/workspace/Dictionaries/Dutch.dic") hunspell("Hij heeft de klok wel horen luiden, maar weet niet waar de klepel hangt", dict = dutch)
Note that if the
dict argument is a string, it will be passed on to the
RStudio users can install various dictionaries via the "Global Options" menu of the IDE. Once these dictionaries are installed they become available to the
spelling package as well.
The best way to install dictionaries on Linux is via the system package manager. For example on if you would like to install the Austrian-German dictionary on Debian or Ubuntu you either need the
sudo apt-get install hunspell-de-at
On Fedora and CentOS / RHEL all German dialects are included with the
sudo yum install hunspell-de
After installing this you should be able to load the dictionary:
dict <- dictionary('de_AT')
If that didn't work, verify that the dictionary files were installed in one of the system directories (usually
If your system does not provide standard dictionaries you need to download them yourself. There are a lot of places that provide quality dictionaries.
On OS-X it is recommended to put the files in
/Library/Spelling/. However you can also put them in your project working directory, or any of the other standard locations. If you wish to store your dictionaries somewhere else, you can make hunspell find them by setting the
DICPATH environment variable. The
hunspell:::dicpath() shows which locations your system searches:
Sys.setenv(DICPATH = "/my/custom/hunspell/dir") hunspell:::dicpath()
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.