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

如何将格式不规则的文本文件转换为列对齐的XLSX文件?

解决.polar文本转Excel(变量列对齐)问题

问题分析

你用pd.read_csv按空格分割并固定27列的方式不匹配数据格式,因为你的数据是变量=值的键值对按组重复(每组包含Beta、L/D等所有变量),这种分割方式会把同一变量的键和值拆到不同列,导致数据截断、错位。

正确处理代码

直接读取文本,逐行解析键值对,按组收集数据后转成Excel:

import pandas as pd

# 读取.polar文件(当作文本处理)
file_path = "InitialModelGeneration_DegenGeom.polar"
data_groups = []
current_group = {}

with open(file_path, 'r') as f:
    # 跳过前6行表头
    for _ in range(6):
        next(f)
    # 逐行处理数据
    for line in f:
        line = line.strip()
        # 跳过空行
        if not line:
            continue
        # 分割变量名和值
        key, value = line.split('=', 1)
        key = key.strip()
        value = float(value.strip())
        current_group[key] = value
        # 当遇到下一个Beta时,说明当前组收集完成(假设Beta是每组的第一个变量)
        if key == 'Beta' and len(current_group) > 1:
            data_groups.append(current_group)
            current_group = {key: value}
    # 加入最后一组数据
    if current_group:
        data_groups.append(current_group)

# 转成DataFrame,每个变量对应一列
df = pd.DataFrame(data_groups)
# 保存为Excel
df.to_excel("InitialModelGenerationVLMResults.xlsx", index=False)

代码说明

  • 跳过前6行无关表头,逐行解析变量=值格式的内容
  • 用字典收集每组的所有变量值,遇到新的Beta时,把当前组存入列表,开始新组
  • 最后将字典列表转成DataFrame,自动按变量名生成列,完美匹配你的需求

内容的提问来源于stack exchange,提问作者Jose De La Pena

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 02:12:21