检查一个字符串是否至少包含单词列表 R 中的 n 个单词

Check if a string contains at least n words out of a list of words R

我只在 Python / Java 中找到了这个问题的答案。

我有一个 data.frame,里面有新闻文章和相应的日期。 我还有一个关键字列表,我想检查每篇文章。

df <- data.frame(c("2015-05-06", "2015-05-07", "2015-05-08", "2015-05-09"), 
                 c("Articel does not contain a key word", "Articel does contain the key word revenue", "Articel does contain two keywords revenue and margin","Articel does not contain the key word margin"))
colnames(df) <- c("date","article")

key.words <- c("revenue", "margin", "among others")

我想出了一个很好的解决方案,如果我只想检查文章中是否包含其中一个词:

article.containing.keyword <- filter(df, grepl(paste(key.words, collapse="|"), df$article))

这很好用,但我真正要寻找的是一个可以设置阈值的解决方案 "article must contain at least n words in order to be filtered",例如,一篇文章必须至少包含 n = 2 个关键字才能被选中通过过滤器。所需的输出如下所示:

  date       article
3 2015-05-08 Articel does contain two keywords revenue and margin

你可以使用 stringr::str_count :

str_count(df$article, paste(key.words, collapse="|"))
[1] 0 1 2 1

可以翻译成这样过滤:

article.containing.keyword <- dplyr::filter(df, str_count(df$article, paste(key.words, collapse="|")) >= 2)
        date                                              article
1 2015-05-08 Articel does contain two keywords revenue and margin