至於dxf文件的格式在之前的博文中已經有詳細的敘述,在此將不做贅述。
from Point import Point
class DXFReaderImpl:
def __init__(self,file):
self.file = file
self.points = [] ## 用於記錄點實體的座標值
self.points_line = [] ## 用於記錄線段的各端點座標值,包括直線和折線兩種線型
self.points_polygon = [] ## 用於紀錄多邊形的頂點座標值
def readDXF(self):
firstLine =""
secondLine = ""
secondLine = self.file.readline().strip()
while secondLine != "EOF":
if firstLine.strip() == "0" and secondLine.strip()== "LWPOLYLINE":
self.readPolyline()
if firstLine.strip() == "0" and secondLine.strip() == "LINE":
self.readLines()
if firstLine.strip() == "0" and secondLine.strip() == "POINT":
pass
firstLine = secondLine
secondLine = self.file.readline().strip()
print "there are " + str(i) + "polyline"
##
## def readPolygon(self):
## pass
## read polyline. In dxf file,polygon is a closed polyline
def readPolyline(self):
counter = 0
numofvertex = 1
flagofPolygon = 0
x = 0
y = 0
firstLine = "LWPOLYLINE"
secondLine = self.file.readline().strip()
pointList = []
while counter<=numofvertex:
if firstLine == "90":
numofvertex = int(secondLine)
if firstLine == "70":
flagofPolygon = int(secondLine)
if firstLine == "10":
x = float(secondLine)
if firstLine == "20":
y = float(secondLine)
pointList.append(Point(x,y))
counter = counter + 1
firstLine = secondLine
secondLine = self.file.readline().strip()
if flagofPolygon == 0:
self.points_line.append(pointList)
else:
self.points_polygon.append(pointList)
def readPoint(self):
firstLine = "POINT"
secondLine = self.file.readline().strip()
x = 0.0
y = 0.0
while firstLine != "30":
if firstLine == "10":
x = float(secondLine)
if firstLine == "20":
y = float(secondLine)
firstLine = secondLine
secondList = self.file.readline().strip();
self.points.append(Point(x,y))
## read straight line
def readLines(self):
x1 = 0.0
y1 = 0.0
x2 = 0.0
y2 = 0.0
firstLine = "POINT"
## secondLine = ""
seondLine = self.file.readline().strip()
while firstLine != "31":
if firstLine == "10":
x1 = float(secondLine)
if firstLine == "20":
y1 = float(secondLine)
if firstLine == "11":
x2 = float(secondLine)
if firstLine == "21":
y2 = float(secondLine)
firstLine = secondLine
secondLine = self.file.readline().strip()
tempLine = []
tempLine.append(Point(x1,y1))
tempLine.append(Point(x2,y2))
self.points_line.append(tempLine)
if __name__=="__main__":
file = open("D:\\test.dxf","r")
reader = DXFReaderImpl(file)
reader.readDXF()
i = 1
for temp in reader.points_polygon:
print " this is the " + str(i) + " polygon"
for points in temp:
print str(points.x) + " " + str(points.y)
i = i + 1
## i = 1
## for temp in reader.points_line:
## print " this is the " + str(i) + " polyline"
## for points in temp:
## print str(points.x) + " " + str(points.y)
## i += 1
print "over"
此段代碼主要用於讀取點,直線,折線,多邊形等四種實體的座標值。