我想在特定位置 ( )將子字串串列 ( word_list) 插入到字串 ( text) 中idx_list
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
idx_list = c(5,16,30,50)
word_list = c("AAA", "BBB", "CCC", "DDD")
我知道我可以在回圈中使用多個可能的函式(gsub、stri_sub 等)。然而,這在大型語料庫上變得相當緩慢。有沒有更有效的解決方案?也許矢量化?
uj5u.com熱心網友回復:
我認為首先從最后一個(最高idx_list)開始很重要,否則所有數字都需要移動。(這當然不難,但倒退似乎更容易。)
# 0 1 2 3 4 5 6 7 8 9 a b c
# 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
idx_list = c(5,16,30,50)
word_list = c("AAA", "BBB", "CCC", "DDD")
作業:
ord <- order(-idx_list)
Reduce(function(S, R) {
paste0(substring(S, 1, R[[1]]-1), R[[2]], substring(S, R[[1]], nchar(S)))
}, Map(list, idx_list[ord], word_list[ord]), text)
# [1] "LoreAAAm ipsum dolBBBor sit amet, cCCConsectetur adipiscinDDDg elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
演練:
ord只是降序,例如word_list[ord] # [1] "DDD" "CCC" "BBB" "AAA"因為我們將使用
Reduce(稍后解釋),我們需要將idx_list[1]和組合word_list[1]在一個引數中,而不是單個引數中;為此,我們使用 將它們組合在一起,將它們Map(list, ...)“壓縮”到一個串列中,每個串列都包含要插入的字符位置和字串:str( Map(list, idx_list[ord], word_list[ord]) ) # List of 4 # $ :List of 2 # ..$ : num 50 # ..$ : chr "DDD" # $ :List of 2 # ..$ : num 30 # ..$ : chr "CCC" # $ :List of 2 # ..$ : num 16 # ..$ : chr "BBB" # $ :List of 2 # ..$ : num 5 # ..$ : chr "AAA"(這可以與任意數量的引數一起使用。)
因為我們需要插入一個字串,然后將另一個字串插入到第一個的結果中,所以 base 函式
Reduce在這里可以很好地作業。第一個 arg 是一個函式,它接受兩個引數:來自前一個呼叫的結果,以及來自Map'd 引數的下一個元素。
uj5u.com熱心網友回復:
扎克福斯特的答案的改編,濃縮成一個單一的功能
reposition_str <- function(string, inject, index) {
inject <- inject[order(index)]
index <- sort(index)
# expand string
split <- substr(rep(string, length(index) 1),
start = c(1, index),
stop = c(index - 1, nchar(string))
)
ord1 <- 2 * (1:length(split)) - 1
ord2 <- 2 * (1:length(inject))
paste(c(split, inject)[order(c(ord1, ord2))], collapse = "")
}
text <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
idx_list <- c(5, 16, 30, 50)
word_list <- c("AAA", "BBB", "CCC", "DDD")
reposition_str(text, word_list, idx_list)
#> [1] "LoreAAAm ipsum dolBBBor sit amet, cCCConsectetur adipiscinDDDg elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
以及速度比較的基準:
bench::mark(reposiion = {reposition_str(text, word_list, idx_list)})
# A tibble: 1 x 13
expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time gc
<bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list> <list>
1 reposiion 69.5us 74.5us 12303. 79.7KB 8.32 5918 4 481ms <chr [1]> <Rprofmem [218 x 3]> <bench_tm [5,922]> <tibble [5,922 x~
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341442.html
上一篇:字串操作熊貓
下一篇:如何列印在我的字串中找到的字符?
