You need to enable JavaScript to run this app. 如何提取PowerDesigner .cdm文件的ID值并存入Pandas DataFrame
优惠活动
大模型
产品
解决方案
定价
更多

如何提取PowerDesigner .cdm文件的ID值并存入Pandas DataFrame

实现方案

首先修正原代码的笔误,再通过正则匹配批量提取ID值即可,完整实现如下:

步骤说明

  • 修复原代码笔误:原代码中收集文件路径时误写为pdm_files.append,需修正为cdm_files.append
  • 编写ID提取函数:读取.cdm文件头部内容,通过正则匹配提取ID属性后的取值
  • 批量调用提取函数,将结果新增为DataFrame的ID列

完整代码

import os
import re
import pandas as pd

# 配置遍历根目录
current_dur = r'Workplace'
cdm_files = []

# 遍历收集所有.cdm文件路径
for root, dirs, files in os.walk(current_dur):
    for file in files:
        if file.endswith('.cdm'):
            cdm_files.append(os.path.join(root, file))

# 生成存储路径的DataFrame
cdm_filesdataframe = pd.DataFrame(cdm_files, columns=['Directory Path'])

# 定义ID提取函数
def extract_cdm_id(file_path):
    try:
        # 只读第一行即可,ID在头部声明中
        with open(file_path, 'r', encoding='utf-16') as f:
            first_line = f.readline()
        # 正则匹配ID取值
        match_res = re.search(r'ID="({[^"}]+})"', first_line)
        return match_res.group(1) if match_res else None
    except Exception as e:
        # 读取/匹配失败返回空值,可根据需要调整异常处理逻辑
        print(f"处理文件{file_path}失败:{str(e)}")
        return None

# 批量提取ID,新增为列
cdm_filesdataframe['ID'] = cdm_filesdataframe['Directory Path'].apply(extract_cdm_id)

# 可选:输出结果查看
print(cdm_filesdataframe.head())

补充说明

  • 示例文件头部标注编码为UTF16,因此读取文件时指定编码为utf-16,如果部分文件编码不一致可调整编码参数或增加编码自适应逻辑
  • 匹配不到ID或者文件读取异常时会返回None,你可以根据实际需求调整异常处理规则,比如过滤无效数据、重新尝试读取等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 06:45:07