匹配并替换R中字符串中的拼写错误的单词

时间:2017-12-08 20:24:53

标签: r regex string text-mining text-processing

我有一个短语列表,我想用一个相似的单词替换某些单词,以防拼写错误。

library(stringr)
a4 <- "I would like a cheseburger and friees please"
badwords.corpus <- c("cheseburger", "friees")
goodwords.corpus <- c("cheeseburger", "fries")

vect.corpus <- goodwords.corpus
names(vect.corpus) <- badwords.corpus

str_replace_all(a4, vect.corpus)
# [1] "I would like a cheeseburger and fries please"

一切都很完美,直到它找到一个类似的字符串,并用另一个字替换它

如果我有如下图案:

"plea",正确的是"please",但是当我执行它时会删除它并将其替换为"pleased"

我正在寻找的是,如果字符串已经正确,则不再修改它,以防它找到类似的模式。

2 个答案:

答案 0 :(得分:1)

也许您需要执行渐进式替换。例如你应该有多套badwordsgoodwords。首先用具有更多字母的badwords替换,以便找不到匹配的模式,然后选择较小的字母。

从您提供的列表中,我将创建2个集:

goodwords1<-c( "three", "teasing") 
badwords1<- c("thre", "teeasing") 

goodwords2<-c("tree", "testing") 
badwords2<- c("tre", "tesing") 

首先用第1组替换然后用第2组替换。您可以创建许多此类集。

答案 1 :(得分:0)

str_replace_all将正则表达式作为模式,因此您可以在每个paste0周围\\b字边界badwords,这样只有在整个单词匹配时才会进行替换:

library(stringr)
string <- c("tre", "tree", "teeasing", "tesing") 
goodwords <- c("tree", "three", "teasing", "testing") 
badwords <- c("tre", "thre", "teeasing", "tesing") 

# Paste word boundaries around badwords
badwords <- paste0("\\b", badwords, "\\b")

vect.corpus <- goodwords 
names(vect.corpus) <- badwords 

str_replace_all(string, vect.corpus) 
[1] "tree"    "tree"    "teasing" "testing"

这样做的好处是您不必跟踪哪些字符串是较长的字符串。

这是badwords粘贴后的样子:

> badwords
[1] "\\btre\\b"      "\\bthre\\b"     "\\bteeasing\\b" "\\btesing\\b"
相关问题