我有几个从 inkspace 生成的 .svg 格式的真实文件。为了验证用 python 编写的程序的精度,我需要从 .svg 文件中读取“矩形”字段、它们的坐标和其他属性,例如轮廓颜色和 id。
我找到了这个主题: Library to parse SVG in Ruby or Python
哪里建议使用 pysvg 库,但我找不到有关 psvg.parser.parse 模块的文档。
有什么建议吗?
谢谢
最佳答案
您可以使用 python xml 解析器,因为 svg 是 xml 的一种类型。使用xpath
或findall
提取你想要的元素并读取元素属性来提取你需要的信息:
import xml.etree.ElementTree as ET
import re
# for parsing svg as a string:
svg = ET.fromstring(svg_string)
# for parsing svg from a file:
svg = ET.parse(svg_file)
rects = svg.findall('rect')
for rect in rects:
width = rect.attrib['width']
height = rect.attrib['height']
x = rect.attrib['x']
y = rect.attrib['y']
请记住,如果 rect
元素是组的一部分,您还必须解析它们所属的所有组的转换。这可能会变得相当棘手。
关于python-2.7 - Python - 从 .svg 文件中读取矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35968744/