【问题标题】:grep and gsub to find patterns and call out patternsgrep 和 gsub 查找模式并调用模式
【发布时间】:2017-05-19 16:35:41
【问题描述】:

我正在尝试在文本中搜索关键字,然后撤回它找到的关键字。

现在我在/可重现的例子:

text <- c("Here is some text about cats and dogs",
          "Here is some text about turtles and chickens",
          "Here is some text about rhinos and elephants")
pattern <- "cat|turtle"
HasPattern <- as.vector(NULL)
for(i in 1:length(text)){
if(sum(grepl(pattern, text[i], ignore.case = TRUE)>0))
   HasPattern <- append(HasPattern, text[i])
}

这个输出的期望结果是:

gsub(grepl(pattern, text), pattern, text) # or something
[1] cat turtle NA

我试过了——

for (i in 1:length(text)){
  if(grepl(pattern, text[i]) == TRUE)
     gsub(text[i], pattern, text[i])
}


sub(text, pattern, text)

gsub(grepl(pattern, text), pattern, text)

在可重现的示例中: HasPattern 给了我一个包含我想要的文本的向量,这很棒。但我也想要它在这些文本中发现的模式的向量。

【问题讨论】:

    标签: arrays r for-loop gsub


    【解决方案1】:

    我们可以使用str_extract

    library(stringr)
    str_extract(text, pattern)
    #[1] "cat"    "turtle" NA      
    

    【讨论】:

    • @MattW。您可以更改模式以使其不区分大小写
    • 这通常是怎么做的? “Cat|cat”是我知道的唯一方法,但我有一个模式的大列表。
    • @MattW 假设你想提取它,然后str_extract(text, "(?i)(C)at|turtle")
    【解决方案2】:

    你也可以在baseR中执行regmatchesgregexpr

    regmat <- regmatches(text,gregexpr(pattern,text))
    regmat[lapply(regmat , length) == 0] <- NA 
    unlist(regmat)
    

    输出:

    > unlist(regmat)
    [1] "cat"    "turtle" NA   
    

    【讨论】:

      猜你喜欢
      • 2014-09-29
      • 2016-05-21
      • 2021-01-09
      • 2011-02-10
      • 2012-07-24
      • 2019-11-04
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多