r - 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"
任何帮助,将不胜感激。谢谢!
解决方案
使用 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=" ")
}
推荐阅读
- mysql - MySQL 8 InnoDB 分区 - 最大分区数
- java - 我应该安装哪个 Java JDK 才能使用 Android Studio
- encoding - url 编码问题 - tableau js api
- php - 如何将 div 添加到最后一个帖子和每 5 个帖子
- r - 仅当满足条件时才在 dplyr 组中过滤,否则不过滤
- python - 合并两个具有相同数量元素的列表并按顺序添加它们
- c# - dotnet core 3.0 在 vs 中打开解决方案时无法找到 dotnetcore sdk
- java - 给定一个字符串,判断它是否是回文,只考虑字母数字字符并忽略大小写
- flutter - 使用pop时如何在flutter中重新加载或调用某些函数initState()
- java - 使用路径找不到元素