python处理文件整理为excel

下面是一个完整的 Python 脚本,可以帮助你在 Linux 下:

  • 解压并读取 /home/lee/low_pow/lib.gz 文件;

  • 从每个 cell (...) {} 中提取你需要的字段:

    • cell 名称(括号里的)

    • arealengthVT type

  • 最终保存为 Excel 表格,每一行为一个 cell 的信息。


✅ 📜 Python 脚本代码(含逐行解释)


python

复制编辑

import gzip             # 读取 .gz 压缩文件
import re               # 使用正则表达式提取数据
import openpyxl         # 创建 Excel 文件

# 1. 设置路径
input_path = '/home/lee/low_pow/lib.gz'
output_excel = '/home/lee/low_pow/cell_info.xlsx'

# 2. 初始化 Excel 表格
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'Cell信息'
ws.append(['Cell 名称', '面积 (area)', '长度 (length)', 'VT 类型'])  # 写入表头

# 3. 编写正则表达式
# 提取整块 cell 信息:cell (名字) { ... }
cell_block_pattern = re.compile(r'cell\s*\((.*?)\)\s*\{(.*?)\}', re.DOTALL)

# 提取各字段
area_pattern = re.compile(r'area\s*[::]\s*([\d.]+)', re.IGNORECASE)
length_pattern = re.compile(r'length\s*[::]\s*(\d+)', re.IGNORECASE)
vt_pattern = re.compile(r'VT\s*type\s*[::]\s*(\w+)', re.IGNORECASE)

# 4. 读取压缩文件并处理内容
with gzip.open(input_path, 'rt', encoding='utf-8') as f:
    content = f.read()  # 读取整个文件为文本

    # 5. 查找所有 cell 块
    matches = cell_block_pattern.findall(content)

    for cell_name, cell_body in matches:
        # 提取字段
        area_match = area_pattern.search(cell_body)
        length_match = length_pattern.search(cell_body)
        vt_match = vt_pattern.search(cell_body)

        # 获取值(没有则为'')
        area = float(area_match.group(1)) if area_match else ''
        length = int(length_match.group(1)) if length_match else ''
        vt_type = vt_match.group(1) if vt_match else ''

        # 写入 Excel 行
        ws.append([cell_name, area, length, vt_type])

# 6. 保存 Excel 文件
wb.save(output_excel)
print(f"✅ 提取完成,Excel 文件保存到:{output_excel}")
 


✅ 📘 脚本逐行解释

行号

作用
import gzip用于读取 .gz 压缩文件格式
import re用正则表达式匹配数据字段
import openpyxl用于写 Excel 文件
cell_block_pattern匹配 cell (XXX) { ... } 的结构,提取 cell 名称和内部内容
area_patternlength_patternvt_pattern{} 内容中分别提取 arealengthVT type
gzip.open(..., 'rt')打开 .gz 文件并以文本模式读取
f.read()读取整个 .lib 文件的内容为字符串
matches = cell_block_pattern.findall(...)找到所有 cell 的定义块,返回一个列表,每个是 (名称, 内容)
search(...).group(1)提取匹配的字段值
ws.append([...])将一行写入 Excel 表格
wb.save(...)保存 Excel 文件到指定路径



 

🎯 目标

我们分成 两个步骤两个脚本

  1. Step 1:从 .lib.gz 提取 cell 数据 → 保存为 JSON 文件

  2. Step 2:从 JSON 文件读取数据 → 转换为 Excel 表格


✅ Step 1:从 .lib.gz 提取并保存为 JSON

📁 文件路径:parse_cells_to_json.py


python

复制编辑

import gzip
import re
import json

# 输入文件路径
input_path = '/home/lee/low_pow/lib.gz'
# 输出 JSON 文件
json_output = '/home/lee/low_pow/cell_data.json'

# 正则表达式匹配 cell 块
cell_block_pattern = re.compile(r'cell\s*\((.*?)\)\s*\{(.*?)\}', re.DOTALL)
area_pattern = re.compile(r'area\s*[::]\s*([\d.]+)', re.IGNORECASE)
length_pattern = re.compile(r'length\s*[::]\s*(\d+)', re.IGNORECASE)
vt_pattern = re.compile(r'VT\s*type\s*[::]\s*(\w+)', re.IGNORECASE)

# 存放结果
data_list = []

with gzip.open(input_path, 'rt', encoding='utf-8') as f:
    content = f.read()

    # 匹配所有 cell
    matches = cell_block_pattern.findall(content)

    for cell_name, cell_body in matches:
        area_match = area_pattern.search(cell_body)
        length_match = length_pattern.search(cell_body)
        vt_match = vt_pattern.search(cell_body)

        data = {
            'cell_name': cell_name.strip(),
            'area': float(area_match.group(1)) if area_match else None,
            'length': int(length_match.group(1)) if length_match else None,
            'vt_type': vt_match.group(1) if vt_match else ''
        }

        data_list.append(data)

# 保存为 JSON 文件
with open(json_output, 'w', encoding='utf-8') as f:
    json.dump(data_list, f, indent=2, ensure_ascii=False)

print(f"✅ 成功写入 JSON 文件:{json_output}")
 


✅ Step 2:从 JSON 转换为 Excel

📁 文件路径:json_to_excel.py


python

复制编辑

import json
import openpyxl

# 输入 JSON 文件路径
json_input = '/home/lee/low_pow/cell_data.json'
# 输出 Excel 文件路径
excel_output = '/home/lee/low_pow/cell_data.xlsx'

# 读取 JSON 数据
with open(json_input, 'r', encoding='utf-8') as f:
    data_list = json.load(f)

# 创建 Excel
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Cell Info"

# 写标题行
ws.append(["Cell 名称", "面积 (area)", "长度 (length)", "VT 类型"])

# 写数据
for item in data_list:
    ws.append([item["cell_name"], item["area"], item["length"], item["vt_type"]])

# 保存 Excel
wb.save(excel_output)

print(f"✅ 成功生成 Excel 文件:{excel_output}")
 




import gzip        # 用于读取 .gz 压缩文件
import re          # 用于正则表达式匹配文本
import json        # 用于写入 JSON 文件

# 输入的 lib.gz 文件路径
input_path = "/home/lee/low_pow/lib.gz"

# 输出的 JSON 文件路径
json_output = "/home/lee/low_pow/level_shifter_cells.json"

# 匹配每一个 cell 的正则表达式:cell (cell_name) { ... }
# 使用 DOTALL 和 MULTILINE 支持跨行匹配
cell_pattern = re.compile(r'cell\s*\((.*?)\)\s*\{(.*?)^\}', re.DOTALL | re.MULTILINE)

# 匹配字段:是否是 level shifter
is_level_shifter_re = re.compile(r'is_level_shifter\s*:\s*(true|false)\s*;', re.IGNORECASE)

# 匹配字段:level shifter 的类型(如 LH、HL)
level_shifter_type_re = re.compile(r'level_shifter_type\s*:\s*(\w+)\s*;', re.IGNORECASE)

# 匹配字段:电源类型,例如 primary_power、primary_ground
pg_type_re = re.compile(r'pg_type\s*:\s*(\w+)\s*;', re.IGNORECASE)

# 匹配字段:引脚方向 input 或 output
direction_re = re.compile(r'direction\s*:\s*(\w+)\s*;', re.IGNORECASE)

# 初始化空列表用于存储所有 cell 的信息
result = []

# 打开并读取压缩文件(文本模式)
with gzip.open(input_path, 'rt', encoding='utf-8') as f:
    content = f.read()  # 读取整个文件内容为字符串

    # 遍历所有匹配到的 cell 块
    for match in cell_pattern.finditer(content):
        cell_name = match.group(1).strip()  # 提取 cell 名称
        body = match.group(2)               # 提取 cell 的内容体

        # 分别查找我们需要的属性字段
        is_level_shifter_match = is_level_shifter_re.search(body)
        level_shifter_type_match = level_shifter_type_re.search(body)
        pg_types = pg_type_re.findall(body)        # 可能多个
        directions = direction_re.findall(body)    # 可能多个

        # 组织一个字典保存当前 cell 的信息
        cell_info = {
            "cell_name": cell_name,
            "is_level_shifter": (
                True if is_level_shifter_match and is_level_shifter_match.group(1).lower() == 'true'
                else False
            ),
            "level_shifter_type": level_shifter_type_match.group(1) if level_shifter_type_match else "",
            "pg_types": pg_types,
            "directions": directions
        }

        # 将该 cell 信息添加到结果列表中
        result.append(cell_info)

# 将结果写入 JSON 文件(美化格式、支持中文)
with open(json_output, 'w', encoding='utf-8') as f:
    json.dump(result, f, indent=2, ensure_ascii=False)

# 控制台输出成功提示
print(f"✅ 已成功提取并写入 JSON 文件:{json_output}")
 

json转为excel

import json                   # 读取 JSON 文件
import openpyxl               # 写入 Excel 表格
from openpyxl import Workbook

# JSON 输入文件路径
json_path = "/home/lee/low_pow/level_shifter_cells.json"

# Excel 输出路径
excel_path = "/home/lee/low_pow/level_shifter_cells.xlsx"

# 读取 JSON 文件内容
with open(json_path, 'r', encoding='utf-8') as f:
    data = json.load(f)

# 创建一个新的 Excel 工作簿
wb = Workbook()

# 激活默认的工作表
ws = wb.active

# 写入表头(第一行)
ws.append(["cell_name", "is_level_shifter", "level_shifter_type", "pg_types", "directions"])

# 写入每个 cell 的信息
for cell in data:
    ws.append([
        cell.get("cell_name", ""),
        cell.get("is_level_shifter", False),
        cell.get("level_shifter_type", ""),
        ", ".join(cell.get("pg_types", [])),       # 列表拼成字符串
        ", ".join(cell.get("directions", []))      # 同上
    ])

# 保存 Excel 文件
wb.save(excel_path)

print(f"✅ JSON 已成功转换为 Excel:{excel_path}")
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

妙妙米奇屋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值