mom=readLines("http://www.norvig.com/big.txt")mom1=tolower(paste(mom,collapse=" "))mom2=strsplit(mom1,"[^a-z]+")mom3=sort(table(mom2),decreasing = TRUE)want=names(mom3)corrector=function(needCorrect){ y=want[adist(needCorrect,want)==min(adist(needCorrect,want),2)] return(c(y,needCorrect)[1])}> corrector("hia")[1] "his"> corrector("andd")[1] "and"> corrector("fof")[1] "of"
Modify a little bit, only the word with same letters(if it exist) will be returned.
mom=readLines("http://www.norvig.com/big.txt")mom1=tolower(paste(mom,collapse=" "))mom2=strsplit(mom1,"[^a-z]+")mom3=sort(table(mom2),decreasing = TRUE)want=names(mom3)corrector=function(needCorrect){ y=want[adist(needCorrect,want)==min(adist(needCorrect,want),2)] if (length(y)>1) { y=y[nchar(y)==nchar(needCorrect)] } return(c(y,needCorrect)[1])}> corrector("fof")[1] "for"
Reference:
http://norvig.com/spell-correct.html
http://www.sumsar.net/blog/2014/12/peter-norvigs-spell-checker-in-two-lines-of-r/
yant07