我正在处理如下的句子
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
}
这是行不通的,我认为 Ano
rexia 这个词中的 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/