Python 实战:自动对齐 C++ 数组代码,提升代码可读性

Python 实战:自动对齐 C++ 数组代码,提升代码可读性

一、前言

在维护 C++ 项目时,常遇到数组元素未对齐的情况,影响可读性。本文提供一个 Python 脚本,自动对齐 C++ 数组,并讲解代码原理与使用方法。

二、问题场景

假设有这样的 C++ 数组:

AlarmInfoAreaA gstAlarmInfoAreaA[]={{0,0, MESSAGE_TYPE2B, SKUI_COLOR_COMMON_LIGHT_YELLOW, SKUI_COLOR_COMMON_NIGHT_YELLOW, MSG_NONE},{1,1, MESSAGE_TYPE2B, SKUI_COLOR_COMMON_LIGHT_YELLOW, SKUI_COLOR_COMMON_NIGHT_YELLOW, MSG_F_CAMERA_BLOCK},{30,6, MESSAGE_TYPE2B, SKUI_COLOR_COMMON_LIGHT_RED, SKUI_COLOR_COMMON_NIGHT_RED, MSG_PLS_BRAKE},// ... 更多行};

对齐后:

AlarmInfoAreaA gstAlarmInfoAreaA[]={{0,0, MESSAGE_TYPE2B, SKUI_COLOR_COMMON_LIGHT_YELLOW, SKUI_COLOR_COMMON_NIGHT_YELLOW, MSG_NONE},{1,1, MESSAGE_TYPE2B, SKUI_COLOR_COMMON_LIGHT_YELLOW, SKUI_COLOR_COMMON_NIGHT_YELLOW, MSG_F_CAMERA_BLOCK},{30,6, MESSAGE_TYPE2B, SKUI_COLOR_COMMON_LIGHT_RED, SKUI_COLOR_COMMON_NIGHT_RED, MSG_PLS_BRAKE},// ... 更多行};

三、完整代码

# -*- coding: utf-8 -*-import re defalign_array(): file_path =r'src\app\wins\MessageWindowConfig.cpp'withopen(file_path,'r', encoding='utf-8')as f: lines = f.readlines() start_idx =None end_idx =Nonefor i, line inenumerate(lines):if'AlarmInfoAreaA gstAlarmInfoAreaA[] = {'in line: start_idx = i if start_idx isnotNoneand line.strip()=='};'and i > start_idx +5: end_idx = i breakif start_idx isNoneor end_idx isNone:print('Array not found')returnprint(f'Found array: line {start_idx+1} to {end_idx+1}') aligned_lines =[]for i inrange(start_idx, end_idx +1): line = lines[i]if'//'in line and'{'notin line: aligned_lines.append(line)continue pattern =r'^\s*\{(\d+),\s*(\d+),\s*([^,]+),\s*([^,]+),\s*([^,]+),\s*([^}]+)\}\s*,?\s*$'match= re.match(pattern, line.strip())ifmatch: alarm_id =int(match.group(1)) icon_id =int(match.group(2)) msg_type =match.group(3).strip() light_color =match.group(4).strip() night_color =match.group(5).strip() string_id =match.group(6).strip() aligned =f' {{{alarm_id:4d}, {icon_id:4d}, {msg_type:16s}, {light_color:32s}, {night_color:33s}, {string_id}}},' aligned_lines.append(aligned +'\n')else: aligned_lines.append(line) new_lines = lines[:start_idx]+ aligned_lines + lines[end_idx+1:]withopen(file_path,'w', encoding='utf-8')as f: f.writelines(new_lines)print('Alignment completed!')if __name__ =='__main__':try: align_array()except Exception as e:print(f'Error: {e}')import traceback traceback.print_exc()

四、代码详解

4.1 编码声明与导入

# -*- coding: utf-8 -*-import re 
  • 第1行:声明 UTF-8 编码(Python 3 可省略)
  • 第2行:导入正则表达式模块

4.2 文件读取

file_path =r'src\app\wins\MessageWindowConfig.cpp'withopen(file_path,'r', encoding='utf-8')as f: lines = f.readlines()
  • r'':原始字符串,反斜杠不转义
  • with open():上下文管理器,自动关闭文件
  • 'r':只读模式
  • encoding='utf-8':UTF-8 编码
  • readlines():读取所有行,返回列表

4.3 查找数组位置

start_idx =None end_idx =Nonefor i, line inenumerate(lines):if'AlarmInfoAreaA gstAlarmInfoAreaA[] = {'in line: start_idx = i if start_idx isnotNoneand line.strip()=='};'and i > start_idx +5: end_idx = i break
  • enumerate():同时获取索引和内容
  • 找到数组开始行,记录 start_idx
  • 找到结束的 };,记录 end_idx 并退出

4.4 正则表达式匹配

pattern =r'^\s*\{(\d+),\s*(\d+),\s*([^,]+),\s*([^,]+),\s*([^,]+),\s*([^}]+)\}\s*,?\s*$'match= re.match(pattern, line.strip())

正则说明:

  • ^\s*:行首空白
  • \{:字面 {
  • (\d+):捕获数字(AlarmID)
  • ,\s*:逗号与空白
  • ([^,]+):非逗号字符(Type、Color 等)
  • ([^}]+):非 } 字符(StringID)
  • \}\s*,?\s*$} 后可选逗号,行尾

4.5 数据提取与格式化

ifmatch: alarm_id =int(match.group(1)) icon_id =int(match.group(2)) msg_type =match.group(3).strip() light_color =match.group(4).strip() night_color =match.group(5).strip() string_id =match.group(6).strip() aligned =f' {{{alarm_id:4d}, {icon_id:4d}, {msg_type:16s}, {light_color:32s}, {night_color:33s}, {string_id}}},' aligned_lines.append(aligned +'\n')
  • match.group(1):第1个捕获组
  • int():转为整数
  • .strip():去除首尾空白
  • f'...':f-string 格式化
  • {变量:格式}:格式化输出
    • :4d:4 位整数,右对齐
    • :16s:16 位字符串,左对齐
  • {{{:输出单个 {(转义)

4.6 文件写入

new_lines = lines[:start_idx]+ aligned_lines + lines[end_idx+1:]withopen(file_path,'w', encoding='utf-8')as f: f.writelines(new_lines)
  • lines[:start_idx]:数组前的行
  • aligned_lines:对齐后的数组行
  • lines[end_idx+1:]:数组后的行
  • 'w':写入模式(覆盖)

4.7 主程序入口

if __name__ =='__main__':try: align_array()except Exception as e:print(f'Error: {e}')import traceback traceback.print_exc()
  • if __name__ == '__main__'::直接运行脚本时执行
  • try/except:异常处理
  • traceback.print_exc():打印完整错误堆栈

五、使用方法

步骤1:保存代码

将代码保存为 align_array.py,放在项目根目录。

步骤2:修改文件路径

修改第5行的文件路径:

file_path =r'你的文件路径\MessageWindowConfig.cpp'

步骤3:运行脚本

python align_array.py 

步骤4:查看结果

脚本会输出:

Found array: line 15 to 243 Alignment completed! 

六、核心知识点总结

知识点说明示例
r''原始字符串r'C:\Users\file.txt'
with open()上下文管理器自动关闭文件
enumerate()获取索引和值for i, line in enumerate(lines)
re.match()正则匹配re.match(pattern, text)
f'...'f-stringf'Hello {name}'
{变量:格式}格式化输出{num:4d} 表示4位整数
if __name__ == '__main__'主程序入口直接运行脚本时执行

七、常见问题

Q1: 文件路径错误怎么办?

A: 使用绝对路径或相对路径,确保路径正确。

Q2: 编码错误怎么办?

A: 确保文件是 UTF-8 编码,或修改 encoding 参数。

Q3: 正则表达式不匹配怎么办?

A: 检查数组格式是否与正则一致,可打印 line 调试。

Q4: 如何修改对齐宽度?

A: 修改格式化字符串中的数字,如 {alarm_id:4d} 改为 {alarm_id:6d}

八、扩展应用

  • 对齐其他格式的数组
  • 批量处理多个文件
  • 自定义对齐规则
  • 添加备份功能

九、总结

本文介绍了:

  1. 使用 Python 自动对齐 C++ 数组
  2. 文件读写、正则匹配、格式化输出
  3. 异常处理与主程序入口

希望本文能帮助你提升代码可读性和维护效率。


十、参考资源