使用python读取dxf文件特定图层的多段线长度

1.导入库

import ezdxf
from ezdxf.math import Vec3
import pandas as pd
import tkinter as tk
from tkinter import filedialog

2.读取DXF文件

root = tk.Tk()
root.withdraw() 

# 打开文件选择对话框,让用户选择文件
file_path = filedialog.askopenfilename(title="Select DXF File", filetypes=[("DXF files", "*.dxf")])

if file_path:
    doc = ezdxf.readfile(file_path)
else:
    print("No file selected.")
msp = doc.modelspace()

3.读取某图层的多段线并计算长度

polylines = [e for e in msp if e.dxftype() == 'LWPOLYLINE' and e.dxf.layer == '图层名称']

line_categories = {}

# 遍历所有多段线
for polyline in polylines:
    points = polyline.get_points()

    points = [(p[0], p[1], 0) if len(p) == 2 else p for p in points]

    for i in range(len(points) - 1):
        # start = Vec3(points[i])
        # end = Vec3(points[i + 1])

        def ensure_vec3(point):
            """Ensure the point is converted to a Vec3 instance."""
            if isinstance(point, Vec3):
                return point
            elif isinstance(point, (list, tuple)):
                # Ensure there are at least three components, adding zeros if necessary
                return Vec3(*point[:3] + (0,) * (3 - len(point)))
            else:
                raise TypeError("Point must be a Vec3, list or tuple.")

        start = ensure_vec3(points[i])
        end = ensure_vec3(points[i + 1])

        # 计算线段的长度
        length = (end - start).magnitude

# 基于颜色属性分类
        category = polyline.dxf.color
        if category not in line_categories:
            line_categories[category] = 0
        line_categories[category] += length
# 输出每个类别的线段总长度
for category, total_length in line_categories.items():
    print(f"Category {category}: Total length = {total_length: .2f} units")

# 将数据整理成DataFrame
data = {'Category': list(line_categories.keys()), 'Total Length': list(line_categories.values())}
df = pd.DataFrame(data)

4.将数据导出到Excel文件

output_filename = 'D:/OneDrive/桌面/output.xlsx'
try:
    df.to_excel(output_filename, index=False, engine='openpyxl')
    print(f"Data has been exported to {output_filename}")
except Exception as e:
    print(f"Failed to export data: {e}")

你可能感兴趣的:(python)