首页 > 解决方案 > R中的否定处理在“not”之前的单词中添加前缀“neg_”

问题描述

我正在对德国客户评论进行情绪分析,并希望实施否定处理。我决定在“not”之后的单词和“not”之前的单词中都添加前缀“neg_”(这对英语可能没有意义,但对德语来说却有意义)。

我已经找到了如何使用此函数将前缀“_neg”添加到“not”之后的单词中:

addprefix <-function(text){  
  words<-unlist(strsplit(text, " "))
  negative <- grepl("\\<not\\>",words,ignore.case=T)
  negate <- append(FALSE,negative)[1:length(words)]
  words[negate==T]<- paste0("neg_",words[negate==T])
  words<-paste(words,collapse=" ")
}

是否有可能在“not”之前的单词中也添加前缀“_neg”?所以评论最初是这样的:

> str_negate("I did not like the product")
[1] "I did not like the product"

目前这个:

> str_negate("I did not like the product")
[1] "I did not neg_like the product"

到最后:

> str_negate("I did not like the product")
[1] "I neg_did not neg_like the product"

任何帮助,将不胜感激。谢谢!

标签: rtext-miningsentiment-analysisnegation

解决方案


使用 not 的索引与 wich 函数的解决方案:

addprefix <-function(text){  
  words<-unlist(strsplit(text, " "))
  negative <- which(grepl("\\<not\\>",words,ignore.case=T))
  to.change = c(negative-1, negative+1)
  to.change = to.change[to.change>0]
  words[to.change] = paste("neg_", words[to.change], sep = '')
  words<-paste(words,collapse=" ")
}


推荐阅读