Hi,
I spent a few time to write a cleaner witch remove empty groups and concatenate identical adjacent ones.
When edit with Inkscape for example, we got one group per view. It's really useful.
A improvement will concatenate non-adjacent similar groups.
Code: Select all
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# clean_fc_svg.py
#
# Copyright 2019 Florian Foinant <ffw_at_2f2v.fr>
#
# 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.
def main(args):
if len(args)!=3 :
print "Clean a FreeCAD exported SVG file"
print "Usage : python clean_fc_svg.py input.svg output.svg"
return 1
input_svg = open(args[1],'r').read()
import re
#remove empty groups
input_svg = re.sub('<g[^<>]*/>\n ','',input_svg)
#parse the xml
import lxml.etree as ET
ET.register_namespace("svg", "http://www.w3.org/2000/svg")
parser = ET.XMLParser(remove_blank_text=True)
root = ET.fromstring(input_svg, parser)
tree = ET.ElementTree(root)
#concatenate identical adjacent groups
last_grp = None
parent_grp = None
for grp in root.iter('{http://www.w3.org/2000/svg}g') :
if len(grp) == 1 :
if not last_grp is None and cmp(grp.attrib,last_grp.attrib)==0 :
last_grp.append(grp[0])
if parent_grp is not None :
parent_grp.remove(grp)
else :
last_grp = grp
else :
parent_grp = grp
#Save the cleaned XML
tree.write(args[2], encoding='utf8', xml_declaration=True, pretty_print=True)
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))