简体   繁体   English

如何使用Python删除SVG文件中的不可见元素?

[英]How to remove invisible elements in SVG files using Python?

How can I clean up SVG files by removing invisible objects or layers with a Python script. 如何通过使用Python脚本删除不可见的对象或图层来清理SVG文件。 Such elements have at least one of the following styles set: 此类元素至少具有以下样式之一:

display: none
opacity: 0
visibility: hidden

I'm considering to use a Regex pattern, but given the complexity of XML, Regex is usually discouraged here. 我正在考虑使用正则表达式模式,但考虑到XML的复杂性,通常不鼓励使用正则表达式。

Would it be an option to use lxml? 是否可以选择使用lxml? I can do some HTML modifications, but I'm not sure about SVG and how to properly save the modified data to the file. 我可以做一些HTML修改,但我不确定SVG以及如何将修改后的数据正确保存到文件中。

Done it: 完成了:

from lxml import etree
doc = etree.parse('/test.svg')
for action, el in etree.iterwalk(doc):
    if el.attrib.get('display', None) == 'none' or el.attrib.get('visibility', None) == 'hidden' or el.attrib.get('opacity', None) == '0':
        el.clear()
with open('/test_out.svg', 'w') as f:
    f.write(u'<?xml version="1.0" encoding="UTF-8"?>\n'+etree.tostring(doc, pretty_print=True))

I hope that will catch all cases. 我希望能抓住所有案件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM