Python SVG parser

2019-01-23 04:01发布

问题:

I want to parse an SVG file using python to extract coordinates/paths (I believe this is listed under the "path" ID, specifically the d="..."/>). This data will eventually be used to drive a 2 axis CNC.

I've searched on SO and Google for libraries that can return the string of such paths so I can further parse it, but to no avail. Does such a library exist?

回答1:

Ignoring transforms, you can extract the path strings from an SVG like so:

from xml.dom import minidom

doc = minidom.parse(svg_file)  # parseString also exists
path_strings = [path.getAttribute('d') for path
                in doc.getElementsByTagName('path')]
doc.unlink()


回答2:

Getting the d-string can be done in a line or two using svgpathtools.

from svgpathtools import svg2paths
paths, attributes = svg2paths('some_svg_file.svg')

paths is a list of svgpathtools Path objects (containing just the curve info, no colors, styles, etc.). attributes is a list of corresponding dictionary objects storing the attributes of each path.

To, say, print out the d-strings then...

for k, v in enumerate(attributes):
    print v['d']  # print d-string of k-th path in SVG