繁体   English   中英

计算包含已定义的较短字符串的字符串数的有效方法

[英]Efficient way to calculate number of strings which contain a defined shorter string

我有一个包含短字符串的字符向量:

short <- c("aaa", "bah", "dju", "kjs")

我想计算下面向量中的字符串数,其中至少有一个上面的短字符串存在。

long <- c("aaajhd", "slilduaaadifh", "sldifjsdbahsdofiusd", "sdflisjdjukjs", "sldifjbak", "sdfoiuwebss", "sdkfuhsd", "sdlfihwoio")

它应输出的数字是4,因为long向量中的4个字符串包含short向量中定义的较短字符串。

我的实际短向量大约是10000个字符串,长大约是1000,所以我正在寻找一种有效的方法来计算它。

谢谢!

这发生在我的笔记本电脑约0.12 seconds其中longshort距离末的注意,并有长度10000个1000没有软件包使用-只生成样本数据。

system.time(num <- length(grep(paste(short, collapse = "|"), long, perl = TRUE)))
   user  system elapsed 
   0.08    0.00    0.12 

相比之下,Reduce / str_count解决方案需要6.5秒。

注意:我们将Ulysses一书中的前1000个和10000个单词作为样本数据。

library(gsubfn)

u <- "http://www.gutenberg.org/files/4300/4300-0.txt"
joyce <- readLines(u)
joycec <- paste(joyce, collapse = " ") 
words <- strapplyc(joycec, "\\w+")[[1]]
short <- head(words, 1000)
long <- head(words, 10000)

我们遍历'short'向量,获取str_count并将其Reduce为单个逻辑向量以获得sum

library(stringr)
sum(Reduce(`|`, lapply(short, str_count, string = long)))
#[1] 4

str_count使用stringi函数,这不依赖于vectorlength

使用上面提供的数据,这只需要0.09秒。

system.time(sum(sapply(regmatches(long, gregexpr(paste(short, collapse = "|"), long, ignore.case = F, perl = T)), length) >= 1))
   User      System verstrichen 
   0.09        0.00        0.09

数据:

library(gsubfn)
u <- "http://www.gutenberg.org/files/4300/4300-0.txt"
joyce <- readLines(u)
joycec <- paste(joyce, collapse = " ") 
words <- strapplyc(joycec, "\\w+")[[1]]
short <- head(words, 1000)
long <- head(words, 10000)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM