#!/usr/bin/env python #dxfpurgeblocks.py - program to purge unused blocks in DXF v.2000 files #Copyright (C) 2005 Fernando Fernandez Pedraza - http://www.fpedraza.com #This program is free software; you can redistribute it and/or #modify it under the terms of the GNU General Public License #as published by the Free Software Foundation; either version 2 #of the License, or (at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import sys import os import string i=0 n=0 blocks=0 blocksfound=0 block=0 nameline=0 lines=[0]*10000000 blocksdata={} blocksindrawing={} blocksdelete={} import fileinput for line in fileinput.input(sys.argv[1]): i=i+1 lines[i]=line #if line contains BLOCKS flag blocks=1 if (string.find(line,"BLOCKS")) <> -1: blocks=1 blocksfound=1 if (blocks): #if line contains ENDSEC flag blocks=0 if (string.find(line,"ENDSEC")) > -1: blocks=0 if (string.find(line,"AcDbBlockBegin")) > -1: block=1 inblock=1 blockbegin=i-9 if (((string.find(line,"AcDbBlockEnd")) > -1) and inblock): inblock=0 blockend=i handle=lines[blockbegin+3] name=lines[blockbegin+11] #ignore some special blocks if (string.find(name,"_Space") < 0): blocksdata[name]=[blockbegin,blockend] #when section 'blocks' end #search again the blocknames we found. #if they appear again we will keep them, else throw away if (blocksfound and blocks==0): if (string.find(line,"AcDbBlockReference") > -1): nameline=i+10 #store found blocks if i==nameline: blocksindrawing[line]=1 #build list of blocks to delete print "blocks in drawing: ", len(blocksindrawing) for k in blocksdata: if (not blocksindrawing.has_key(k)): blocksdelete[k]=blocksdata[k] print "blocks to purge:", len(blocksdelete) # delete unused blocks from 'BLOCKS' section for k in blocksdelete: n=n+1 if (n%100==0): print "Deleted", n, "unused blocks" for j in range(blocksdelete[k][0],blocksdelete[k][1]+1): lines[j]="" f=open("copy_of_"+sys.argv[1],"w") for i in lines: if i: f.write(i) f.close