我有
txt <- "{a} is to {b} what {c} is to {d}"
key <- c(a='apple', b='banana', c='chair', d='door')
fun <- function(x) key[x]
Run Code Online (Sandbox Code Playgroud)
我想快速转换txt为key:
"apple is to banana what chair is to door"
Run Code Online (Sandbox Code Playgroud)
我知道我可以gsub像这样重复使用(或类似的东西):
for (v in names(key)) txt <- gsub(sprintf('{%s}',v), fun(v), txt, fixed = TRUE)
txt
# [1] "apple is to banana what chair is to door"
Run Code Online (Sandbox Code Playgroud)
但我的txt和key都很长,所以上面是有问题的。我想知道是否有更快的方法,例如:
gsub(sprintf('{%s}',names(key)), key, fixed = TRUE) # Does not work
gsub('\\{(a|b|c|d)\\}', fun(...), txt, fixed = TRUE) # Does not work
Run Code Online (Sandbox Code Playgroud)
是否可以?谢谢。
我们可以glue在将 key 的元素创建为对象后使用
list2env(as.list(key), .GlobalEnv)
glue::glue(txt)
Run Code Online (Sandbox Code Playgroud)
-输出
apple is to banana what chair is to door
Run Code Online (Sandbox Code Playgroud)
如果我们不想在全局环境中创建对象,也可以在 the 中添加key[with ,然后使用gsub{}glue
glue::glue(gsub("\\{([^}]+)\\}", "{key['\\1']}", txt))
apple is to banana what chair is to door
Run Code Online (Sandbox Code Playgroud)
或者正如 @Robert Hacken 在评论中提到的,.envir会更紧凑
glue::glue(txt, .envir=as.list(key))
apple is to banana what chair is to door
Run Code Online (Sandbox Code Playgroud)
和glue_data():
library(glue)
glue_data(key, txt)
# apple is to banana what chair is to door
Run Code Online (Sandbox Code Playgroud)
在 R 中使用 Python 的原始示例:
library(reticulate)
list2env(as.list(key), envir = .GlobalEnv)
py_run_string('res = f"{r.a} is to {r.b} what {r.c} is to {r.d}"')
py$res
# "apple is to banana what chair is to door"
Run Code Online (Sandbox Code Playgroud)