我正在尝试从http://kanjivg.tagaini.net/解析.svg文件,但我无法成功提取内部信息.
编辑1 :(完整档案)http://www.filedropper.com/0f9ab
部分0f9ab.svg
看起来像这样:
<svg xmlns="http://www.w3.org/2000/svg" width="109" height="109" viewBox="0 0 109 109">
<g id="kvg:StrokePaths_0f9ab" style="fill:none;stroke:#000000;stroke-width:3;stroke-linecap:round;stroke-linejoin:round;">
<g id="kvg:0f9ab" kvg:element="?">
<g id="kvg:0f9ab-g1" kvg:element="?" kvg:position="top" kvg:radical="general">
<path id="kvg:0f9ab-s1" kvg:type="?a" d="M53.26,9.38c0.99,0.99,1.12,2.09,1.12,3.12c0,0.67,0.06,8.38,0.06,13.01"/>
<path id="kvg:0f9ab-s2" kvg:type="?a"
</g>
</g>
</g>
Run Code Online (Sandbox Code Playgroud)
我的.py文件:
import lxml.etree as ET
svg = ET.parse('0f9ab.svg')
print(svg) # <lxml.etree._ElementTree object at 0x7f3a2f659ec8>
# AttributeError: 'lxml.etree._ElementTree' object has no attribute 'tag'
print(svg.tag)
# TypeError: 'lxml.etree._ElementTree' object is not subscriptable
print(svg[0])
# TypeError: 'lxml.etree._ElementTree' object is not iterable
for child in svg:
print(child)
# None
print(svg.find("./svg"))
# []
print(svg.findall("//g"))
# []
print(svg.xpath("//g"))
Run Code Online (Sandbox Code Playgroud)
我尝试了各种我能想到的操作,但没有任何东西从.svg文件中获取任何数据.我想提取汉字(日语字符)kvg:element="kanji"
(在不同的深度级别).
lxml
了错误的包?kvg:element="
,但我想以正确的方式提取xml/svg.xmltodict
以前使用过,但我的代码变得非常混乱kvg:element
,因为它们处于不同的深度级别..parse()
返回一个ElementTree,它代表整个树.要查询单个节点,您需要一个Element,很可能是树的根元素.
用以下代码替换部分代码:
xml = ET.parse('0f9ab.svg')
svg = xml.getroot()
print(svg) # <lxml.etree._ElementTree object at 0x7f3a2f659ec8>
Run Code Online (Sandbox Code Playgroud)
而且我认为你会取得一些成功.
另请注意,.findall()
需要相对路径,在您的情况下,还需要命名空间限定符:
print(svg.findall(".//{http://www.w3.org/2000/svg}g"))
Run Code Online (Sandbox Code Playgroud)