You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R或Python正则提取文本文件中TS时间戳对应数据生成独立DataFrame

解决方法

原正则匹配规则未适配TS块的多行结构,可按行定位拆分的方式处理,代码如下:

library(dplyr)

# 读取文件所有行,去除首尾空白和空行
all_lines <- trimws(readLines("D:/D50 python/D50.bc", warn = FALSE))
all_lines <- all_lines[nzchar(all_lines)]

# 定位所有TS 0行,提取对应的时间戳
ts_line_idx <- grep("^TS 0 ", all_lines)
ts_timestamp <- as.numeric(sub("^TS 0 (\\S+)", "\\1", all_lines[ts_line_idx]))

# 划分每个TS对应的数据行范围,生成独立DataFrame
ts_df_list <- mapply(
  FUN = function(start, end, ts_val) {
    # 读取当前TS块下的所有数据行
    df <- read.table(
      text = all_lines[(start + 1):(end - 1)],
      header = FALSE,
      sep = "",
      col.names = paste0("V", 1:14)
    )
    # 添加TS时间列
    df$ts <- ts_val
    return(df)
  },
  start = ts_line_idx,
  end = c(ts_line_idx[-1], length(all_lines) + 1),
  ts_val = ts_timestamp,
  SIMPLIFY = FALSE
)

# 可选:给每个DataFrame命名对应TS值
names(ts_df_list) <- paste0("ts_", ts_timestamp)

结果说明

  • ts_df_list为列表格式,每个元素对应一个TS时间戳的独立DataFrame,可直接提取做后续列运算
  • 数据列默认命名为V1到V14,可根据实际参数含义替换列名
  • 自动适配每个TS下的数千行数据,无需调整正则规则

内容的提问来源于stack exchange,提问作者ZVY545

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 20:06:03