【问题标题】:Search within a string from a list of keywords and tag keywords that occur从出现的关键字和标记关键字列表中搜索字符串
【发布时间】:2017-01-03 13:45:29
【问题描述】:

我有一组陈述

statement <- as.matrix(c("the cat sat on the mat", 
                          "the dog ran up the hill",
                          "the dog ran up the hill to the mat"))

和关键字列表

keywords &lt;- as.matrix(c("cat", "mat", "dog", "hill"))

我想在我的关键字列表中搜索语句并标记出现的关键字,即有结果

statement                             keywords
the cat sat on the mat                cat, mat 
the dog ran up the hill               dog, hill
the dog ran up the hill to the mat    dog, hill, mat

我在想我能做到的一种方法是像使用 grep 一样

statement[grep("cat", statement$V1, ignore.case = TRUE), "keywords"] <- "cat"
statement[grep("mat", statement$V1, ignore.case = TRUE), "keywords"] <- "mat"

... 等等,但首先,这不会为我标记所有出现的关键字。其次,如果我试图找到一种方法,当我有一个大列表时,比如说 1000 个关键字和 500 个语句,它只会变得笨拙。

您对此有何建议?有没有使用 grep 的方法或者是否有任何包可以挖掘文本并从预定列表中返回关键字?

谢谢!

【问题讨论】:

  • 这些必须是矩阵对象吗?或者向量就足够了?
  • @benjamin 向量在这种情况下就足够了
  • @DarshanBaral 谢谢!这真的很有帮助

标签: r string-matching


【解决方案1】:

你可以使用stringi包,

library(stringi)
sapply(stri_extract_all_regex(statement[,1], 
                       paste(keywords[,1], collapse = '|')), toString)

#[1] "cat, mat"      "dog, hill"     "dog, hill, mat"

【讨论】:

    【解决方案2】:
    keywords <- c("cat", "mat", "dog", "hill")
    m = sapply(keywords, grepl, statement)
           cat   mat   dog  hill
    [1,]  TRUE  TRUE FALSE FALSE
    [2,] FALSE FALSE  TRUE  TRUE
    [3,] FALSE  TRUE  TRUE  TRUE
    
    apply(m,1, function(y) paste0(colnames(m)[y], collapse=","))
    [1] "cat,mat"      "dog,hill"     "mat,dog,hill"
    

    或在一行中:将statement 的每一行用“”分隔,然后使用%in% 检查存在哪些单词以及paste 它们全部

    apply(statement, 1, function(i) paste0(x[x %in% unlist(strsplit(i, " "))], collapse=","))
    [1] "cat,mat"      "dog,hill"     "mat,dog,hill"
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-04
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    相关资源
    最近更新 更多