如何用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
相关产品推荐
相关产品推荐

