簡體   English   中英

使用多個模式從列表中包含的一些但不是所有字符串中提取和組合多個子字符串並返回到 R 中的列表

[英]Extract & combine multiple substrings using multiple patterns from some but not all strings contained in list & return to list in R

我想找到一種優雅且易於操作的方式來:

  1. 從作為列表元素包含的一些(但不是全部)字符串中提取多個子字符串(每個列表元素僅由一個長字符串組成)
  2. 用這些多個子字符串替換各自的原始長字符串
  3. 將每個列表元素中的子字符串折疊為 1 個字符串
  4. 根據需要返回包含替換子字符串和未觸及的長字符串的相同長度的列表。

這個問題是我之前問題的后續(雖然不同): 用 substring 替換某些列表元素的字符串 請注意,我不想在所有列表元素上運行正則表達式模式,只想在正則表達式適用的那些元素上運行。

我知道最終結果可以由str_replacesub通過匹配要更改的整個字符串並返回捕獲組捕獲的文本來傳遞,如下所示:

library(stringr)
myList <- as.list(c("OneTwoThreeFourFive", "mnopqrstuvwxyz", "ghijklmnopqrs", "TwentyTwoFortyFourSixty"))
fileNames <- c("AB1997R.txt", "BG2000S.txt", "MN1999R.txt", "DC1997S.txt")
names(myList) <- fileNames
is1997 <- str_detect(names(myList), "1997")

regexp <- ".*(Two).*(Four).*"
myListNew2 <- myList
myListNew2[is1997] <- lapply(myList[is1997], function(i) str_replace(i, regexp, "\\1££\\2"))

## This does return what I want:
myListNew2
$AB1997R.txt
[1] "Two££Four"

$BG2000S.txt
[1] "mnopqrstuvwxyz"

$MN1999R.txt
[1] "ghijklmnopqrs"

$DC1997S.txt
[1] "Two££Four"

但我更願意這樣做而不必匹配整個原始文本(因為,例如,匹配很長的文本所需的時間;多個正則表達式模式的復雜性以及將它們編織在一起以成功匹配整個字符串的難度)。 我想使用單獨的正則表達式模式來提取子字符串,然后用這些提取物替換原始字符串。 我想出了以下方法,這很有效。 但肯定有更簡單、更好的方法! llply

patternA <- "Two"
patternB <- "Four"
x <- myList[is1997]
x2 <- unlist(x)
stringA <- str_extract (x2, patternA)
stringB <- str_extract (x2, patternB)
x3 <- mapply(FUN=c, stringA, stringB, SIMPLIFY=FALSE)
x4 <- lapply(x3, function(i) paste(i, collapse = "££"))
x5 <- relist(x4,x2)
myListNew1 <- replace(myList, is1997, x5)
myListNew1

$AB1997R.txt
[1] "Two££Four"

$BG2000S.txt
[1] "mnopqrstuvwxyz"

$MN1999R.txt
[1] "ghijklmnopqrs"

$DC1997S.txt
[1] "Two££Four"

可能是這樣的,我已經擴展了您正在尋找的模式以展示它如何變得具有適應性:

library(stringr)
patterns <- c("Two","Four","Three")
hits <- lapply(myList[is1997], function(x) {
  out <- sapply(patterns, str_extract, string=x)
  paste(out[!is.na(out)],collapse="££")
})
myList[is1997] <- hits

#[[1]]
#[1] "Two££Four££Three"
#
#[[2]]
#[1] "mnopqrstuvwxyz"
#
#[[3]]
#[1] "ghijklmnopqrs"
#
#[[4]]
#[1] "Two££Four"

提取多個匹配項並組合成字符串

library(stringi)

patterns <- 'Two|Three|Four'

hits <- stri_join_list(stri_extract_all_regex(myList[is1997],patterns),sep = '££')

myList[is1997] <- hits

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM