具体来说,我想在“not”或“n't”后面的单词中添加前缀“not_”
str_negate <- function(x) {
gsub("not ","not not_",gsub("n't ","n't not_",x))
}
或者我想你可以使用 strsplit:
str_negate <- function(x) {
str_split <- unlist(strsplit(x=x, split=" "))
is_negative <- grepl("not|n't",str_split,ignore.case=T)
negate_me <- append(FALSE,is_negative)[1:length(str_split)]
str_split[negate_me==T]<- paste0("not_",str_split[negate_me==T])
paste(str_split,collapse=" ")
}
无论哪种方式给你:
> str_negate("They didn't sell the company")
[1] "They didn't not_sell the company"
> str_negate("They did not sell the company")
[1] "They did not not_sell the company"