1. 程式人生 > 實用技巧 >Python之處理svg檔案中的style屬性

Python之處理svg檔案中的style屬性

功能介紹

主要是把svg圖片中的style屬性內部的值,放到外部。

demo.xml

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" xml:space="preserve"
     preserveAspectRatio="none"><defs></defs>
    <g transform="matrix(0.439528 0 0 0.439528 330.719764 171.306754)" id="圖層_1">
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;"
      transform=" translate(-341.275, -21.812)" d="M 682.55 43.624 H 0 V 0 h 682.55 V 43.624 z" stroke-linecap="round"/>
</g>
</svg>

正則實現

from xml.dom import minidom
import re

def update_xml(xml_file_path):
    """
    功能:style屬性移外部
    :param xml_file_path: xml 檔案路徑
    :return: 返回 xml 檔案
    """
    dom = minidom.parse(xml_file_path)
    root = dom.documentElement
    svg_dom = root.toxml()
    styles = re.findall('style="[^"]+"', svg_dom)
    try:
        for style in styles:
            data_list = []
            attrs = re.findall('([\w-]+):\s*([^;]+)', style)
            name, value = attrs[-1]
            sub_value = value.replace("\"", "")
            attrs[-1] = (name, sub_value)
            for attr in attrs:
                key, value = attr
                if not value in ['butt']:
                    data_list.append(key + '="' + value + '"')
            svg_dom = svg_dom.replace(style, " ".join(data_list))
        with open(xml_file_path, 'w', encoding='utf-8') as f:
            f.write(svg_dom)
        return xml_file_path
    except Exception as e:
        print(f'update_xml : {e}')


if __name__ == '__main__':
    update_xml('demo.xml')

更新後的demo.xml

<svg preserveAspectRatio="none" version="1.1" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"><defs/>
    <g id="圖層_1" transform="matrix(0.439528 0 0 0.439528 330.719764 171.306754)">
<path d="M 682.55 43.624 H 0 V 0 h 682.55 V 43.624 z" stroke-linecap="round" stroke="none" stroke-width="1"
      stroke-dasharray="none" stroke-dashoffset="0" stroke-linejoin="miter" stroke-miterlimit="4" fill="rgb(0,0,0)"
      fill-rule="nonzero" opacity="1" transform=" translate(-341.275, -21.812)"/>
</g>
</svg>