r 排除带有关键词的句子

标签 r string grepl negation

我正在处理如下的句子

    Has no anorexia
    She denies anorexia
    Has anorexia
    Positive for Anorexia

我的目标是排除包含denies, denied, no这样的词的句子,只保留厌食症的积极迹象。

最终的结果应该是

     Has anorexia
     Positive for Anorexia

我用 grepl 函数试过这个选项

     negation <- c("no","denies","denied")
     if (grepl(paste(negation,collapse="|"), Anorexia_sentences[j]) == TRUE){

     Anorexia_sentences[j] <- NA

     }

这是行不通的,我认为 Anorexia 这个词中的 no 导致了一些问题。非常感谢任何有关如何解决此问题的建议。

最佳答案

corpus 库的功能类似于 stringr 等价物,但在term 级别而不是字符 水平。这有效:

library(corpus)
negation <- c("no", "denies", "denied")
text <- c("Has no anorexia", "She denies anorexia", "Has anorexia",
          "Positive for Anorexia", "Denies anorexia")
text[!text_detect(text, negation)]
## [1] "Has anorexia"          "Positive for Anorexia"

如果您想要一个只使用基础 R 的解决方案,请改用以下内容:

pattern <- paste0("\\b(", paste(negation, collapse = "|"), ")\\b")
text[!grepl(pattern, text, ignore.case = TRUE)]

关于r 排除带有关键词的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46695638/

相关文章:

r - 将角色分成几部分

R,将 dplyr::mutate 与包含 grepl() 的 ifelse 一起使用会产生意外结果

r - 使用另一列的字符串添加列

r - CCA分析: Error in rowSums(X) : 'x' must be numeric

r - 连续日值的总和

r - 查找字符串是否一次在多列中匹配并返回逻辑矩阵?

java - System.out.println 中使用的字符串是否也会创建新的不可变对象(immutable对象)?

R:是否可以矢量化/加速这个双循环?

r - 在 R 中按列中的行值和行中的列值对 data.frame 进行排序

c++ - 用空格填充字符串有时会破坏字符串迭代器