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

如何用Python优雅解析C数组并提取指定索引元素至文件?

优雅解析C数组并提取指定元素的Python实现

没问题,我给你写一个实用且扩展性强的Python脚本,完美匹配你的需求,还能轻松适配更多提取场景。

完整实现代码

import re

def parse_data(input_file_path, output_file_path, extraction_rules):
    # 读取目标C文件内容
    with open(input_file_path, 'r') as in_file:
        file_content = in_file.read()
    
    # 用正则精准匹配数组内容:适配带换行、空格的C数组写法
    array_pattern = re.search(r'my_array\[\w+\]\s*=\s*{([^}]+)}', file_content, re.DOTALL)
    if not array_pattern:
        raise ValueError("文件里没找到目标数组my_array哦")
    
    # 清理元素格式:去掉多余空格、换行,分割成干净的元素列表
    raw_elements = array_pattern.group(1).strip()
    clean_elements = [elem.strip() for elem in raw_elements.split(',') if elem.strip()]
    
    # 写入输出文件
    with open(output_file_path, 'w') as out_file:
        for label, indices in extraction_rules.items():
            # 处理不同类型的索引输入:单个索引、索引范围、自定义索引列表
            if isinstance(indices, int):
                selected_elements = [clean_elements[indices]]
            elif isinstance(indices, range):
                selected_elements = clean_elements[indices.start:indices.stop]
            else:
                selected_elements = [clean_elements[i] for i in indices]
            
            # 按要求格式写入
            out_file.write(f"{label}: {','.join(selected_elements)}\n")

# 示例调用
if __name__ == "__main__":
    # 定义提取规则:键是标注文本,值是要提取的索引(灵活支持多种形式)
    extract_rules = {
        "Version Number": 0,
        "Date": range(1, 11)  # range是左闭右开,所以取到索引10的话stop设为11
    }
    try:
        parse_data("myfile.c", "output.txt", extract_rules)
        print("提取完成!结果已经写到output.txt里啦")
    except Exception as e:
        print(f"出小问题了:{e}")

代码说明

  1. 正则匹配:用re.DOTALL参数让正则能跨换行匹配数组内容,不管数组元素是一行还是多行排列都能正确捕获。
  2. 元素清理:自动去掉元素前后的空格、换行符,确保得到的元素列表干净整洁。
  3. 灵活的提取规则:
    • 单个索引(比如0):提取指定位置的单个元素
    • 索引范围(比如range(1,11)):提取连续一段元素
    • 自定义索引列表(比如[0,3,5]):提取任意分散的索引元素
  4. 安全的文件操作:用with语句自动管理文件句柄,不用手动关闭文件,避免资源泄漏。

测试效果

针对你给出的myfile.c中的数组,运行脚本后,output.txt的内容会完全符合你的期望:

Version Number: 0x10
Date: 0x12,0x13,0x14,0x15,0x23,0x01,0x02,0x04,0x07,0x08

如果之后需要提取其他索引的元素,只需要修改extract_rules字典就行,非常方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:48:58