【问题标题】:Check if a string contains at least n words out of a list of words R检查字符串是否包含单词列表 R 中的至少 n 个单词
【发布时间】:2017-10-16 20:27:05
【问题描述】:

我只在 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))

这很好用,但我真正在寻找的是一个解决方案,我可以设置一个阈值,例如“文章必须包含至少 n 个单词才能被过滤”,例如,一篇文章必须至少包含n = 2 个关键字被过滤器选择。所需的输出如下所示:

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

【问题讨论】:

  • rowSums(sapply(key.words, grepl, df$article)) &gt;= 2?
  • @docendo discimus 你的解决方案对我来说也很好!

标签: r string filter grepl contain


【解决方案1】:

你可以使用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

【讨论】:

    猜你喜欢
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多