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

如何用Python将MTPL格式文件转换为Pandas DataFrame?

实现思路与代码示例

核心思路

逐行解析MTPL文件,先提取每个Test块的名称,再拆分块内的属性键值对,最后将所有条目整理成指定结构的Pandas DataFrame。

分步实现

  • 读取并预处理文件:用Python内置文件操作读取MTPL文件,逐行处理时跳过空白行和仅含大括号的行。
  • 捕获Test名称:当行以Test 开头时,提取该行的Test名称(去掉Test 前缀)。
  • 解析属性键值对:在{}包裹的块内,对包含=的行进行拆分,提取属性名(Type)和属性值(Value),同时清理值两端的引号和末尾的分号。
  • 生成DataFrame:将每个Test名称与对应的属性键值对组成三元组,存入列表后转换为带指定列名的DataFrame。

代码实现

import pandas as pd

def mtpl_to_dataframe(file_path):
    rows = []
    current_test_name = None

    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            cleaned_line = line.strip()
            # 跳过无效行
            if not cleaned_line or cleaned_line in ('{', '}'):
                continue
            
            # 提取Test名称
            if cleaned_line.startswith('Test '):
                current_test_name = cleaned_line[5:].strip()
                continue
            
            # 处理属性行
            if '=' in cleaned_line and current_test_name:
                # 按第一个等号拆分,避免值里含等号的情况
                type_col, value_col = cleaned_line.split('=', 1)
                type_name = type_col.strip()
                # 清理值的引号和分号
                value = value_col.strip().strip('";')
                rows.append([current_test_name, type_name, value])
    
    # 转换为目标DataFrame
    df = pd.DataFrame(rows, columns=['Name', 'Type', 'Value'])
    return df

# 使用示例:替换为你的MTPL文件路径
result_df = mtpl_to_dataframe('test.mtpl')
print(result_df)

额外说明

  • 如果MTPL文件有注释(比如#开头的行),可以在循环中添加if cleaned_line.startswith('#'): continue跳过注释行。
  • 代码用split('=', 1)确保即使属性值包含等号,也不会被错误拆分,提升了鲁棒性。

内容的提问来源于stack exchange,提问作者Shi Jie Tio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 21:05:15