Python SVG 解析器

Posted

技术标签:

【中文标题】Python SVG 解析器【英文标题】:Python SVG parser 【发布时间】:2013-03-29 06:41:20 【问题描述】:

我想使用 python 解析 SVG 文件以提取坐标/路径(我相信这列在“路径”ID 下,特别是 d="..."/>)。该数据最终将用于驱动 2 轴 CNC。

我在 SO 和 Google 上搜索了可以返回此类路径字符串的库,以便我可以进一步解析它,但无济于事。有这样的图书馆吗?

【问题讨论】:

你也可以看看 VPYPE。可以作为独立的 CLI,也可以作为代码 (Python)。 【参考方案1】:

忽略变换,您可以像这样从 SVG 中提取路径字符串:

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()

【讨论】:

你对什么时候转换很重要有什么建议吗? @Veech:如果有转换,它可能很重要。不幸的是,处理它们需要 很多 更多代码。 是的,我开始意识到这一点。我发现cjlano's svg repo 已经足够好了(有一些修改)。 并非每个有效的 XML 都是有效的 SVG。【参考方案2】:

使用svgpathtools 可以在一两行内完成获取 d-string。

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

paths 是 svgpathtools Path 对象的列表(仅包含曲线信息,没有颜色、样式等)。 attributes 是对应字典对象的列表,存储了每条路径的属性。

比如说,打印出 d-strings 然后...

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

【讨论】:

【参考方案3】:

问题是关于提取路径字符串,但最终需要线条绘制命令。根据minidom的回答,我添加了用svg.path解析路径来生成画线坐标:

#!/usr/bin/python3
# requires svg.path, install it like this: pip3 install svg.path

# converts a list of path elements of a SVG file to simple line drawing commands
from svg.path import parse_path
from svg.path.path import Line
from xml.dom import minidom

# read the SVG file
doc = minidom.parse('test.svg')
path_strings = [path.getAttribute('d') for path
                in doc.getElementsByTagName('path')]
doc.unlink()

# print the line draw commands
for path_string in path_strings:
    path = parse_path(path_string)
    for e in path:
        if isinstance(e, Line):
            x0 = e.start.real
            y0 = e.start.imag
            x1 = e.end.real
            y1 = e.end.imag
            print("(%.2f, %.2f) - (%.2f, %.2f)" % (x0, y0, x1, y1))

【讨论】:

这就是我想要的! svg.pathsvgpathtools 更具可读性,但 svgpathtools 包装得很好。如果您想了解如何通过 SVG 文件绘制曲线,则可以阅读 svg.path,但可以与 svgpathtools 一起使用

以上是关于Python SVG 解析器的主要内容,如果未能解决你的问题,请参考以下文章

类似Python的URL解析器和操纵器

Python之迭代器和列表解析

网页解析器

Python 之父的解析器系列之三:生成一个 PEG 解析器

用python编写一个快速解析器

Python网页解析器使用实例详解