【问题标题】:Match and replace misspelled words in a string in R匹配和替换R中字符串中的拼写错误的单词
【发布时间】:2018-05-23 03:07:13
【问题描述】:

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

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"

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

【问题讨论】:

  • 能不能举个反例,我不清楚?
  • string&lt;- c("tre", "tree", "teeasing", "tesing") goodwords&lt;-c("tree", "three", "teasing", "testing") badwords&lt;- c("tre", "thre", "teeasing", "tesing") vect.corpus &lt;- goodwords names(vect.corpus) &lt;- badwords a &lt;- str_replace_all(string, vect.corpus) "tree" **"treee"** "teasing" "testing"

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


【解决方案1】:

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

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

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

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

先用第一组替换,然后再用第二组替换。您可以创建许多这样的集合。

【讨论】:

    【解决方案2】:

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

    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"
    

    【讨论】:

      猜你喜欢
      • 2020-10-26
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-10
      • 2016-09-14
      相关资源
      最近更新 更多