【发布时间】: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 给了我一个包含我想要的文本的向量,这很棒。但我也想要它在这些文本中发现的模式的向量。
【问题讨论】: