[英]gsubfn | Replace text using variables in Substitution
我正在尝试删除围绕我要保留的内容的文本块。 所以我想分配变量,因为文本可能很长。 这是我正在尝试做的一个例子。 [不删除文字]
Text<-'This is an example text [] test'
topheader<-'This'
bottomheader<-'test'
gsubfn(".", list(topheader = "", bottomheader = ""), Text)
[1] "This is an example text [] test"
Goal: "is an example text []"
我认为这是您要寻找的解决方案之一:
# Your data:
Text<-'This is an example text [] test'
topheader<-'This'
bottomheader<-'test'
# A possible solution fn
gsubfn <- function(text, th, bh, th.replace="", bh.replace="") {
answer <- gsub(text,
pattern=paste0(th," (.*) ",bh),
replacement=paste0(th.replace,"\\1",bh.replace)
)
return(answer)
}
# Your req'd answer
gsubfn(text=Text,th=topheader,bh=bottomheader)
# Another example
gsubfn(text=Text,th=topheader,bh=bottomheader,th.replace="@@@ ",bh.replace=" ###")
您可以将搜索词折叠成一个正则表达式字符串。
Test <- 'This is an example text testing [] test'
top <- "This"
bottom <- "test"
arg <- c(top, bottom)
arg <- paste(arg, collapse="|")
arg <- gsub("(\\w+)", "\\\\b\\1\\\\b", arg)
Test.c <- gsub(arg, "", Test)
Test.c <- gsub("[ ]+", " ", Test.c)
Test.c <- gsub("^[[:space:]]|[[:space:]]$", "", Test.c)
Test.c
# "is an example text []"
或使用magrittr
管
library(magrittr)
c(top, bottom) %>%
paste(collapse="|") %>%
gsub("(\\w+)", "\\\\b\\1\\\\b", .) %>%
gsub(., "", Test) %>%
gsub("[ ]+", " ", .) %>%
gsub("^[[:space:]]|[[:space:]]$", "", .) -> Test.c
Test.c
# "is an example text []"
或使用循环
Test.c <- Test
words <- c(top, bottom)
for (i in words) {
Test.c <- gsub(paste0("\\\\b", i, "\\\\b"), "", Test)
}
Test.c <- gsub("[ ]+", " ", Test.c)
Test.c <- gsub("^[[:space:]]|[[:space:]]$", "", Test.c)
Test.c
# "is an example text []"
1)gsubfn这里有几个问题:
gsubfn
(和gsub
)中的正则表达式必须与您要处理的字符串匹配,但是点仅与单个字符匹配,因此它永远不能与This
匹配或test
这4个字符串。 使用"\\\\w+"
代替。
在list(a = x)
, a
必须是常量,而不是变量。 明确地写出名称,或者如果它们在变量中,则使用setNames
。
从而解决问题中的代码:
library(gsubfn)
trimws(gsubfn("\\w+", list(This = "", text = ""), Text))
## [1] "is an example [] test"
或就标头变量而言:
L <- setNames(list("", ""), c(topheader, bottomheader))
trimws(gsubfn("\\w+", L, Text))
## [1] "is an example [] test"
请注意,这将替换出现的topheader和bottomheader,而不仅仅是开头和结尾的内容; 但是,这似乎是最接近您的代码(可能已足够)。
2)sub另一种可能是这个简单的sub
sub("^This (.*) text$", "\\1", Text)
[1] "is an example [] test"
或就标头变量而言:
pat <- sprintf("^%s (.*) %s$", topheader, bottomheader)
sub(pat, "\\1", Text)
## [1] "is an example [] test"
更新:固定(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.