gsubfn |使用Substitution中的变量替换文本

时间:2017-11-30 19:45:47

标签: r string-substitution gsubfn

我正在尝试删除包含我想要保留的文本块。所以我想分配变量,因为文本可能很长。这是我想要做的一个例子。 [不删除文字]

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 []" 

3 个答案:

答案 0 :(得分:0)

我认为这是您正在寻找的解决方案之一:

# 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=" ###")

答案 1 :(得分:0)

您可以将搜索字词折叠为正则表达式字符串。

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 []"

答案 2 :(得分:0)

1)gsubfn 这里有几个问题:

  • gsubfn(和gsub)中的正则表达式必须与您要处理的字符串匹配,但点只匹配单个字符,因此它永远不会匹配Thistest,它们是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)

相关问题