在R中快速进行部分字符串匹配

20
给定一个字符串向量texts和一个模式向量patterns,我想找到每个文本的任何匹配模式。 对于小数据集,可以使用grepl在R中轻松完成:
patterns = c("some","pattern","a","horse")
texts = c("this is a text with some pattern", "this is another text with a pattern")

# for each x in patterns
lapply( patterns, function(x){
  # match all texts against pattern x
  res = grepl( x, texts, fixed=TRUE )
  print(res)
  # do something with the matches
  # ...
})

这个解决方案是正确的,但无法扩展。即使在中等大小的数据集(约500个文本和模式)下,这段代码的速度非常慢,每秒只能解决大约100个案例,这在现代计算机上是可笑的,考虑到这只是一个简单的字符串局部匹配,没有正则表达式(使用fixed=TRUE设置)。甚至将lapply并行化也无法解决问题。 有没有一种有效的方式来重新编写这段代码呢?

谢谢, Mulone


你的模式总是单个词吗?你只是想知道patterns中的每个元素是否出现在texts的一个或多个元素中(还是需要知道它们出现在texts的哪个/哪些元素中)? - jbaums
2个回答

17
使用 stringi 包 - 它甚至比 grepl 更快。请查看基准测试!我使用了 @Martin-Morgan 的帖子中的文本。
require(stringi)
require(microbenchmark)

text = readLines("~/Desktop/pg100.txt")
pattern <-  strsplit("all the world's a stage and all the people players", " ")[[1]]

grepl_fun <- function(){
    lapply(pattern, grepl, text, fixed=TRUE)
}

stri_fixed_fun <- function(){
    lapply(pattern, function(x) stri_detect_fixed(text,x,NA))
}

#        microbenchmark(grepl_fun(), stri_fixed_fun())
#    Unit: milliseconds
#                 expr      min       lq   median       uq      max neval
#          grepl_fun() 432.9336 435.9666 446.2303 453.9374 517.1509   100
#     stri_fixed_fun() 213.2911 218.1606 227.6688 232.9325 285.9913   100

# if you don't believe me that the results are equal, you can check :)
xx <- grepl_fun()
stri <- stri_fixed_fun()

for(i in seq_along(xx)){
    print(all(xx[[i]] == stri[[i]]))
}

9

您是否准确地描述了您的问题和您看到的性能?这里有威廉·莎士比亚的全部作品,以及针对它们的查询。

text = readLines("~/Downloads/pg100.txt")
pattern <- 
    strsplit("all the world's a stage and all the people players", " ")[[1]]

您所表达的含义似乎比实际性能更低?

> length(text)
[1] 124787
> system.time(xx <- lapply(pattern, grepl, text, fixed=TRUE))
   user  system elapsed 
  0.444   0.001   0.444 
## avoid retaining memory; 500 x 500 case; no blank lines
> text = text[nzchar(text)]
> system.time({ for (p in rep(pattern, 50)) grepl(p, text[1:500], fixed=TRUE) })
   user  system elapsed 
  0.096   0.000   0.095 

我们预计模式和文本的长度(元素数量)会呈线性扩展。看来我对莎士比亚的记忆出了些问题。

> idx = Reduce("+", lapply(pattern, grepl, text, fixed=TRUE))
> range(idx)
[1] 0 7
> sum(idx == 7)
[1] 8
> text[idx == 7]
[1] "    And all the men and women merely players;"                       
[2] "    cicatrices to show the people when he shall stand for his place."
[3] "    Scandal'd the suppliants for the people, call'd them"            
[4] "    all power from the people, and to pluck from them their tribunes"
[5] "    the fashion, and so berattle the common stages (so they call"    
[6] "    Which God shall guard; and put the world's whole strength"       
[7] "    Of all his people and freeze up their zeal,"                     
[8] "    the world's end after my name-call them all Pandars; let all"    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接