【问题标题】:R: simple keyword detectionR:简单的关键字检测
【发布时间】:2017-08-02 21:44:50
【问题描述】:

我想检查一组“关键字”中的 any 是否出现在字符串中。因此,对于下面的 "text",结果应该是 TRUE(或 1),而对于 text_2,结果应该是 FALSE(或 0)。

keywords <- c("one", "two", "three", "four") #set of keywords
text <- "Blah blah one blah two" 
text_2 <- "Blah blah" 

我尝试了一些关于 str_detect 的变体,但我卡住了。

例如,我知道我没有正确使用此功能,但是:

> keywords <- c("motor", "car", "ford") #list of keywords
> text <- "I am looking to buy a ford" #string I'd like to check
> ifelse(str_detect(text, pattern = keywords), 1, 0)
[1] 0 0 1

有更好的方法吗?

【问题讨论】:

    标签: r stringr grepl


    【解决方案1】:

    试试这个...

    any(sapply(keywords,grepl,text))
    [1] TRUE
    
    any(sapply(keywords,grepl,text_2))
    [1] FALSE
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-22
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2014-01-13
      相关资源
      最近更新 更多