gpt4 book ai didi

regex - R中字符向量的快速转义/解析

转载 作者:行者123 更新时间:2023-12-04 03:00:59 25 4
gpt4 key购买 nike

要在json中编码字符串,需要使用反斜杠对几个保留字符进行转义,并且每个字符串都必须用双引号引起来。当前,jsonlite包使用基础R中的deparse函数实现了此功能:

deparse_vector <- function(x) {
stopifnot(is.character(x))
vapply(x, deparse, character(1), USE.NAMES=FALSE)
}

这可以解决问题:
test <- c("line\nline", "foo\\bar", "I said: \"hi!\"")
cat(deparse_vector(test))

但是,对于大向量, deparse变慢。另一种实现方式是分别对每个字符进行 gsub:
deparse_vector2 <- function(x) {
stopifnot(is.character(x))
if(!length(x)) return(x)
x <- gsub("\\", "\\\\", x, fixed=TRUE)
x <- gsub("\"", "\\\"", x, fixed=TRUE)
x <- gsub("\n", "\\n", x, fixed=TRUE)
x <- gsub("\r", "\\r", x, fixed=TRUE)
x <- gsub("\t", "\\t", x, fixed=TRUE)
x <- gsub("\b", "\\b", x, fixed=TRUE)
x <- gsub("\f", "\\f", x, fixed=TRUE)
paste0("\"", x, "\"")
}

这有点快,但也并不太多,也有点丑陋。有什么更好的方法可以做到这一点? (最好没有其他依赖项)

script可用于比较实现:
> system.time(out1 <- deparse_vector1(strings))
user system elapsed
6.517 0.000 6.523
> system.time(out2 <- deparse_vector2(strings))
user system elapsed
1.194 0.000 1.194

最佳答案

我不知道仅用R代码来实现此目的的更快方法,但是我确实决定尝试用C语言实现它,并封装在一个名为deparse_vector3的R函数中。这很粗糙(而且我离C语言专家还很远),但它似乎适用于您的示例:https://gist.github.com/wch/e3ec5b20eb712f1b22b2

在我的系统(Mac,R 3.1.1)上,deparse_vector2deparse_vector快20倍以上,这比测试中获得的5倍大得多。

我的deparse_vector3函数仅比deparse_vector2快3倍。可能还有改进的空间。

> system.time(out1 <- deparse_vector1(strings))
user system elapsed
8.459 0.009 8.470
> system.time(out2 <- deparse_vector2(strings))
user system elapsed
0.368 0.007 0.374
> system.time(out3 <- deparse_vector3(strings))
user system elapsed
0.120 0.001 0.120

不过,我认为这不会正确处理非ASCII字符编码。这是R源中如何处理编码的示例: https://github.com/wch/r-source/blob/bfe73ecd848198cb9b68427cec7e70c40f96bd72/src/main/grep.c#L588-L630

编辑:这似乎可以处理UTF-8,虽然我可能在测试中遗漏了一些东西。

关于regex - R中字符向量的快速转义/解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25609174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com