簡體   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