如何修改Python代码实现.dat与.dml合并生成指定格式Excel
需求说明
需将给定的.dat数据文件与.dml元数据文件合并,转换为Excel格式,要求:
- Excel首行为字段名
- 第二行为对应数据类型
- 后续为数据行
示例文件
.dat数据示例
Sweta|dhanbad|1000|1 Manish|dhanbad|2000|2 Priyanka|dhanbad|3000|3
.dml元数据示例
record string("|") name /* VARCHAR(10)*/; string("|") address; // VARCHAR(40) decimal("|") salary; integer("\n") I'd; end
现有代码问题
用户已编写以下Python代码,但目前无法正确分离字段名和数据类型,无法满足Excel格式要求:
import pandas as pd dml_file = 'src.dml' with open(dml_file, "r") as dml: dml_lines = dml.readlines() col = [] for line in dml_lines[1:-1]: if line: col.append(line.strip(';').strip())
解决方案
修改代码,从.dml文件中分别提取字段名和对应的数据类型,再读取.dat数据,最后构造符合要求的Excel结构:
import pandas as pd import re # 读取并解析.dml文件 dml_file = 'src.dml' field_names = [] data_types = [] # 匹配数据类型、字段名和注释里的类型的正则 pattern = r'^(\w+)\([^)]+\)\s+(\w+)\s*(?:/\*([^*]+)\*/|//\s*([^\n]+))?;' with open(dml_file, "r") as dml: for line in dml.readlines(): line = line.strip() # 跳过record、end和空行 if line in ('record', 'end') or not line: continue # 解析每一行 match = re.match(pattern, line) if match: base_type = match.group(1) field_name = match.group(2) # 优先取注释里的类型,没有则用基础类型 type_comment = match.group(3) or match.group(4) data_type = type_comment.strip() if type_comment else base_type field_names.append(field_name) data_types.append(data_type) # 读取.dat文件 dat_file = 'src.dat' df = pd.read_csv(dat_file, sep='|', names=field_names) # 构造Excel的表头行:首行字段名,第二行数据类型 type_row = pd.DataFrame([data_types], columns=field_names) final_df = pd.concat([type_row, df], ignore_index=True) # 保存为Excel final_df.to_excel('output.xlsx', index=False, header=False)
代码说明
- 解析.dml文件:使用正则表达式匹配每行的基础数据类型、字段名,以及注释中定义的具体数据类型(如
VARCHAR(10)),分别存入两个列表。 - 读取.dat数据:用
pandas.read_csv以|为分隔符读取数据,指定列名为提取的字段名。 - 构造Excel结构:将数据类型行作为第一行(对应Excel的第二行),数据行紧随其后,保存时不保留默认表头,让字段名作为Excel的首行。
内容的提问来源于stack exchange,提问作者Sweta Rawani
相关产品推荐
相关产品推荐

