通过应用transform - reduce size来简化SVG

Mar*_*oma 5 python svg

我经常有一些像这样的结构的SVG:

<svg:g
  transform="translate(-251.5,36.5)"
  id="g12578"
  style="fill:#ffff00;fill-opacity:1">
  <svg:rect
width="12"
height="12"
x="288"
y="35.999958"
id="rect12580"
style="fill:#ffff00;fill-opacity:1;stroke:#000000;stroke-width:1" />
</svg:g>
Run Code Online (Sandbox Code Playgroud)

我想直接将translate应用于坐标并删除tranform-attribute:

<svg:g
  id="g12578"
  style="fill:#ffff00;fill-opacity:1">
  <svg:rect
width="12"
height="12"
x="36.5"
y="69.499958"
id="rect12580"
style="fill:#ffff00;fill-opacity:1;stroke:#000000;stroke-width:1" />
</svg:g>
Run Code Online (Sandbox Code Playgroud)

你知道一个简化SVG的脚本/程序吗?还是用于解析SVG的python-snipplet?

这个脚本适用于我的特殊情况,但我想要一个总是有效的:

#http://epydoc.sourceforge.net/stdlib/xml.dom.minidom.Element-class.html
from xml.dom.minidom import parse, parseString
import re

f = open('/home/moose/mathe/svg/Solitaire-Board.svg', 'r')

xmldoc = parse(f)

p = re.compile('translate\(([-\d.]+),([-\d.]+)\)', re.IGNORECASE)

for node in xmldoc.getElementsByTagName('svg:g'):
  transform_dict = node.attributes["transform"]
  m = p.match(transform_dict.value)
  if m:
    x = float(m.group(1))
    y = float(m.group(2))
  child_rectangles = node.getElementsByTagName('svg:rect') 
  for rectangle in child_rectangles:
    x_dict = rectangle.attributes["x"]
    y_dict = rectangle.attributes["y"]
    new_x = float(x_dict.value) + x
    new_y = float(y_dict.value) + y
    rectangle.setAttribute('x', str(new_x))
    rectangle.setAttribute('y', str(new_y))
  node.removeAttribute('transform')

print xmldoc.toxml()
Run Code Online (Sandbox Code Playgroud)

我认为如果可以删除transform属性,svg的大小可以大大减少而不会降低质量.如果该工具能够降低坐标精度,那么明智地删除不必要的区域,组和样式就会很棒.

Roe*_*eeK 0

1)可以用正则表达式进行解析和编辑。您可以轻松获得平移值以及 x,y。
2)如果您检查了minidom,并确定您唯一的问题是“:”,那么只需替换“:”,编辑您需要的内容,然后将其重新替换为“:”。
3)你可以使用这个问题:Is there any scripting SVG editor? 了解如何更好地解析这种 XML 格式。