gpt4 book ai didi

r - 如何用R解析INI之类的配置文件?

转载 作者:行者123 更新时间:2023-12-02 14:28:00 25 4
gpt4 key购买 nike

有没有R函数可以解析INI like configuration files

搜索时我只找到 this discussion

最佳答案

这是一个精确的答案 same question 2007 年 r-help 上的内容(感谢 @Spacedman 指出这一点):

Parse.INI <- function(INI.filename) 
{
connection <- file(INI.filename)
Lines <- readLines(connection)
close(connection)

Lines <- chartr("[]", "==", Lines) # change section headers

connection <- textConnection(Lines)
d <- read.table(connection, as.is = TRUE, sep = "=", fill = TRUE)
close(connection)

L <- d$V1 == "" # location of section breaks
d <- subset(transform(d, V3 = V2[which(L)[cumsum(L)]])[1:3],
V1 != "")

ToParse <- paste("INI.list$", d$V3, "$", d$V1, " <- '",
d$V2, "'", sep="")

INI.list <- list()
eval(parse(text=ToParse))

return(INI.list)
}

实际上,我编写了一个简短且可能有缺陷的函数(即未涵盖所有极端情况),现在对我有用:

read.ini <- function(x) {
if(length(x)==1 && !any(grepl("\\n", x))) lines <- readLines(x) else lines <- x
lines <- strsplit(lines, "\n", fixed=TRUE)[[1]]
lines <- lines[!grepl("^;", lines) & nchar(lines) >= 2] # strip comments & blank lines
lines <- gsub("\\r$", "", lines)
idx <- which(grepl("^\\[.+\\]$", lines))
if(idx[[1]] != 1) stop("invalid INI file. Must start with a section.")

res <- list()
fun <- function(from, to) {
tups <- strsplit(lines[(from+1):(to-1)], "[ ]*=[ ]*")
for (i in 1:length(tups))
if(length(tups[[i]])>2) tups[[i]] <- c(tups[[i]][[1]], gsub("\\=", "=", paste(tail(tups[[i]],-1), collapse="=")))
tups <- unlist(tups)
keys <- strcap(tups[seq(from=1, by=2, length.out=length(tups)/2)])
vals <- tups[seq(from=2, by=2, length.out=length(tups)/2)]
sec <- strcap(substring(lines[[from]], 2, nchar(lines[[from]])-1))
res[[sec]] <<- setNames(vals, keys)
}
mapply(fun, idx, c(tail(idx, -1), length(lines)+1))
return(res)
}

其中 strcap 是一个将字符串大写的辅助函数:

strcap <- function(s) paste(toupper(substr(s,1,1)), tolower(substring(s,2)), sep="")

还有一些 C 解决方案可以解决这个问题,例如 inihlibini这可能有用。不过,我没有尝试过。

关于r - 如何用R解析INI之类的配置文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21064761/

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