使用stri_replace_all_fixed匹配精确单词

时间:2016-05-16 20:40:39

标签: regex r stringr

嗨:我如何让R替换" no"与"不是"但不能取代"不是"用" nott"

下面的代码与我当前的词典非常相似,但与另一个用一些标准化词代替否定词的词典没有关系。

#patterns
replace<-('no')
#replacements
with<-c('not')
#data frame
neg<-data.frame(replace=replace, with=with)
#text to modify
out<-c('not acceptable no good')
#current code
stri_replace_all_fixed(out, neg$replace, neg$with, vectorize_all=FALSE)

1 个答案:

答案 0 :(得分:3)

您需要传递一个与no完整匹配的正则表达式:

> replace<-('\\bno\\b')  ## <= \b is a word boundary
> with<-c('not')
> neg<-data.frame(replace=replace, with=with)
> out<-c('not acceptable no good')
> stri_replace_all_regex(out, neg$replace, neg$with, vectorize_all=FALSE)
[1] "not acceptable not good"