代码之家  ›  专栏  ›  技术社区  ›  Sharif Amlani

如何在一列文本中搜索多个单词

  •  0
  • Sharif Amlani  · 技术社区  · 5 年前

    我在用一个词的向量。我想检查这个向量中的任何单词是否存在于字符串中。如果有,我希望它返回一个布尔值。

    words <- c("I", "overflow", "game", "peace")
    string <- c("I went to the store", "I love stack overflow", "need overflow to help me", "cant wait for the pandemic to end")
    
    #Within each string, the result should be:
    [1] TRUE TRUE TRUE FALSE
    
    

    2 回复  |  直到 5 年前
        1
  •  1
  •   Ronak Shah    5 年前

    你可以粘贴 words grepl .

    grepl(paste0('\\b', words, '\\b', collapse = '|'), string)
    #[1]  TRUE  TRUE  TRUE FALSE
    

    stringr

    library(stringr)
    str_detect(string, str_c('\\b', words, '\\b', collapse = '|'))
    

    我用过词界( \\b )以使 I 不符合 Ian 等。

        2
  •  0
  •   Gwang-Jin Kim    5 年前

    虽然是大数据,但是 apply 函数族和 grepl

    res <- sapply(paste0("\\b", words, "\\b"), function(w) grepl(w, string))
    rownames(res) <- string
    

    该矩阵显示了在哪个句子中找到的单词:

    res
    ## gives:
                                      \\bI\\b \\boverflow\\b \\bgame\\b \\bpeace\\b
    I went to the store                  TRUE          FALSE      FALSE       FALSE
    I love stack overflow                TRUE           TRUE      FALSE       FALSE
    need overflow to help me            FALSE           TRUE      FALSE       FALSE
    cant wait for the pandemic to end   FALSE          FALSE      FALSE       FALSE
    

    使用 apply(X=res, MARGIN=1, function(row) Reduce( , row)) 然后可以将行折叠起来,以确定是否找到其中的任何单词:

                  I went to the store             I love stack overflow 
                                 TRUE                              TRUE 
             need overflow to help me cant wait for the pandemic to end 
                                 TRUE                             FALSE