【发布时间】:2020-05-31 14:47:04
【问题描述】:
我想挑选出数学方程的 SVG 中使用的每个符号的位置和字体大小。
我正在使用 Python XML 解析库:xml.etree.ElementTree (https://docs.python.org/3/library/xml.etree.elementtree.html)。
这是我正在使用的 SVG 示例:
example_svg = '''<svg style="vertical-align:-10.2252022445128pt" xmlns="http://www.w3.org/2000/svg" width="193pt" height="31pt" viewBox="-1 -1 193 31">
<path d="M43.875 16.305h20.426" fill="none" stroke-width=".914" stroke="#000" stroke-miterlimit="10"></path>
<g font-family="MathFont" font-size="13.5">
<text y="11.168" x="45.874">3</text>
<text y="11.168" x="52.532">????</text>
<text y="28.382" x="50.758">4</text>
</g>
<g font-family="MathFont" font-size="9.45">
<text y="6.327" x="60.453">3</text></g>
</svg>'''
在 Latex 中,等式是 $\frac{3x^3}{4}$。
使用以下代码几乎可以满足我的所有需求,但我似乎无法将其与组文本中的属性联系起来。理想情况下,我希望输出为 (symbol, y_coord, x_coord, font-family, font-size)。
import xml.etree.ElementTree as ET
root = ET.fromstring(example_svg)
for tag in root.findall('.//{http://www.w3.org/2000/svg}text'):
symbol = tag.text
y_coord = tag.get('y')
x_coord = tag.get('x')
print(symbol, y_coord, x_coord)
【问题讨论】:
-
字体和大小在另一个标签中,而不是在
<text>中。所以这就是为什么你看不到他们。etree是否允许访问元素的 parent? -
@usr2564301 这是一个有用的评论,它引导我到stackoverflow.com/questions/2170610/… 我只是在跟踪它,看看它是否能解决问题。
-
@usr2564301 感谢您的帮助。我认为一切都源于此:对于 root.getiterator() 中的父级:对于父级中的子级:print(child.tag, child.attrib, parent.tag, parent.attrib)
-
另一种选择可能对 XML 更“自然”:循环遍历所有
<g>元素,并在其中循环遍历它们的<text>子元素。