R grepl 检查字符串是否包含我们所有的单词

标签 r regex nlp

寻找一种快速且不冗长的解决方案来检查字符串是否包含给定单词向量的所有元素。我提出了一些想法,但感觉我错过了一些东西,特别是因为检查字符串是否包含任何单词有一个非常简洁的解决方案。

我尝试过的:

# Example data
strings <- c(
  "never going to do this again",
  "never again", 
  "will repeat", 
  "never repeat", 
  "again tomorrow"
)

# Words we are looking for
ourWords <- c("never", "again")

# Check if string contains any of our words
grepl(paste0(ourWords, collapse = "|"), strings, , fixed = TRUE)
# Very neat solution but **not** what I am looking for    

# Check if string contains **all** of our words
grepl(ourWords[1], strings, fixed = TRUE) & 
  grepl(ourWords[2], strings, fixed = TRUE)
# This is verbose, not very scalable, and seems inefficient

# Even less efficient alternative
vapply(
  strsplit(strings, split = " "), 
  function(x)  sum(ourWords %in% x) == length(ourWords),
  logical(1)
)

最佳答案

您可以结合使用 sprintf 和多个前瞻:

strings <- c(
  "never going to do this again",
  "never again", 
  "will repeat", 
  "never repeat", 
  "again tomorrow"
)

ourWords <- c("never", "again")

regex <- paste0(sprintf("(?=.*%s)", ourWords), collapse = '')
strings[grepl(regex, strings, perl = TRUE)]

在这种情况下的产量

[1] "never going to do this again" "never again"                 

这里的想法是使用多个前瞻。

关于R grepl 检查字符串是否包含我们所有的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48949006/

相关文章:

python - 带条件的正则表达式大写单词

node.js - 新闻文章分类(通过 NLP 进行主题/实体分析?);最好在 Node.js 中

r - 在R中按组对所有行重复检查

r - .md中的xtable,然后在rstudio中以pdf形式显示,显示%注释

R更改NA值

c - 在 c 和正则表达式中使用 flex

java - 正则表达式 - 如何确保两个字符之间或从开始到某个字符之间仅出现 1 个字符实例

machine-learning - 使用 NLP 从字符串中查找意图的良好资源

java - Java 中使用位置索引进行流标记

macos - R 到剪贴板在 Mac 上不起作用