【问题标题】:Search for the first matching text for dictionary terms in R在 R 中搜索字典术语的第一个匹配文本
【发布时间】:2016-09-16 06:38:56
【问题描述】:

我有一本带术语的字典

terms <- c("hello world", "great job")
terms <- as.data.frame(terms)

,我想在包含文档的附加 data.frame 中搜索第一个匹配项

doc <- c("i would like to say hello worlds", "hey friends hello world everyone", "i'm looking for a great job", "great job")
docs <- as.data.frame(doc)

期望的结果:

foundtext <- c("i would like to say hello worlds","i'm looking for a great job")
output <- cbind(terms, foundtext)

感谢您的帮助!

【问题讨论】:

    标签: r regex match string-matching stringr


    【解决方案1】:

    此解决方案非常简单且有效。正如我所说,我没有为此使用正则表达式。

    doc <- c("i would like to say hello worlds", "hey friends hello world everyone", "i'm looking for a great job", "great job")
    docs <- as.data.frame(doc)
    docs$match <- "not found" #or just empty
    for (i in terms){
    
        docs$new <- grepl(i, docs$doc, perl=TRUE)
        docs$match[docs$new=="TRUE"] <- i
        next
    
    }
    docs <- subset(docs,,1:2)
    docs$dupl <- !duplicated(docs$match, fromLast=FALSE)
    docs <- subset(subset(docs, dupl=="TRUE"),,1:2)
    docs
    

    【讨论】:

      猜你喜欢
      • 2014-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      相关资源
      最近更新 更多