首页 > 解决方案 > 从 .txt 文件中提取一些数据

问题描述

经过一个漫长的早晨,我放弃了!

我有以下文本文件: StationLog.txt

包含以下内容:

Version      = 2.0
StationName  = STN67_P70
BeginTime    = 2017-10-06.03:25:00
EndTime      = 2017-10-06.03:55:00
IgnoreNo     = 5000
PumpedVolume = 0

我需要提取 BeginTime、EndTime 和 StationName,这些标题很好,作为输入另一段代码的值。

这个想法是我不必手动执行,因为及时会有很多这些文件。

到目前为止,我必须遵循各种其他指南:

a <- read.fwf("StationLog.txt", c(37,100), stringsAsFactors=FALSE)
a <- a[grep("=", a$V1), ]
a <- cbind(
  do.call( rbind, strsplit(a$V1, "=\\s+") )

但是碰壁了,任何帮助将不胜感激!

标签: rtextautomation

解决方案


基于read.table函数,您可以使用参数来做您想做的事情。

如果每行只有一个=,并且 BeginTime、EndTime 和 StationName 在所有文件中具有相同的写法,则以下建议将起作用:

read.table(
  file            ="StationLog.txt",
  header          =FALSE, # No column names
  sep             ="=",   # separator character
  strip.white     =TRUE,  # remove multiple white character
  row.names       =1,     # the first column contains the rownames
  stringsAsFactors=FALSE
)[c("BeginTime", "EndTime", "StationName"), # extract the 3 infos based on their names corresponding to the rownames
  ,drop=FALSE] # keep the data.frame format

结果:

                             V2
BeginTime   2017-10-06.03:25:00
EndTime     2017-10-06.03:55:00
StationName           STN67_P70

推荐阅读