繁体   English   中英

从非表格文件中提取信息并存储为 tibble

[英]extract information from non tabular file and store as tibble

我使用了一个静态库,它在文本文件中导出了它的 output。 我希望从文本文件中提取一些信息。 我可以复制粘贴,但我想自动执行从 output 文本文件中提取信息的过程。

以下是文本文件中的示例 output。

如何提取 LL(0) 和 LL(final) 以及相应的值并将它们存储在 tibble 中?

谢谢

Date: XX-XX-XXXX
Time: XX:XX PM

Model: Binary Logit Model

LL(0)                            : -376.3789
Number of Inputs                 :  500
LL(final)                        : -114.1382
Rho-sq                           :  0.512

我们可以使用readLines读取.txt ,使用grep对具有“LL”的行进行子集化,通过删除字符,使用正则表达式提取数字组件,直到:后跟零个或多个空格

v1 <- sub(".*:\\s*", "", grep("^LL\\(", txt, value = TRUE))
tibble(v1 = as.numeric(v1))
# A tibble: 2 x 1
#    v1
#  <dbl>
#1 -376.
#2 -114.

如果我们也想要 header

library(data.table)
library(magrittr)
read.table(text = grep("^LL\\(", txt, value = TRUE), 
        sep = ":", strip.white = TRUE) %>% 
     data.table::transpose(., make.names = "V1")
#     LL(0) LL(final)
#1 -376.3789 -114.1382

数据

txt <- readLines('file.txt')

类似以下的内容将满足问题的要求。 为了让grep得到它们,括号必须被转义。

library(tibble)

fun_extract <- function(text, pattern){
  i <- grep(pattern, text)
  x <- sub("^.*:(.*$)", "\\1", text[i])
  as.numeric(x)
}

lines <- readLines("data.txt")

ll0 <- "LL\\(0\\)"
llfinal <- "LL\\(final\\)"

tbl <- tibble(
  `LL(0)` = fun_extract(lines, ll0), 
  `LL(final)` = fun_extract(lines, llfinal)
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM