4
\$\begingroup\$

I often use Inkscape for generating SVG images. However, these images contain data which doesn't seem to affect the visual output, so I want to remove it. To do that, I wrote the following code:

"""
Use: python inkscape-svg-shortener.py [original_file] [destination]
"""

import os
import sys

try:
    original_file, target = sys.argv[1:3]
    with open(original_file) as f:
        text = f.read()
except FileNotFoundError:
    quit("ERROR: File does not exist!")
except IndexError:
    print(__doc__)
    quit("ERROR: Not enough values given!")

if os.path.isfile(target):
    if input(f"A file named {target} already exists! Overwrite? (y)  ") != "y":
        quit("Aborted!")

quote = "\""
pairs = {
    "<!--": "-->",
    "<metadata": "</metadata>",
    "<?xml": "?>",
    " version=\"": quote,
    "<inkscape:perspective": "/>",
    "<sodipodi:namedview": "/>",
    "xmlns:dc=\"": quote,
    "xmlns:rdf=\"": quote,
    "xmlns:cc=\"": quote,
    "stroke-linecap:butt;": "",
    "fill-opacity:1;": "",
    "stroke-linejoin:miter;": "",
    "font-weight:normal;": "",
    "stroke-opacity:1;": "",
    "stroke-dasharray:none": "",
    "stroke-miterlimit:": ";",
    "fill-rule:": ";",
    "xml:space=\"": quote,
    "letter-spacing:0px;": "",
    "font-style:normal;": "",
    "word-spacing:0px;": "",
    "stroke:none;": "",
    "xmlns:sodipodi=\"": quote,
    "xmlns:inkscape=\"": quote
}

if "<use" not in text:
    pairs[" id=\""] = quote

for start, end in pairs.items():
    while start in text:
        startpos = text.find(start)
        endpos = text.find(end, startpos + len(start)) + len(end)
        text = text[:startpos] + text[endpos:]

for a in ("sodipodi", "inkscape"):
    while a in text:
        start = text.find(a)
        sep1 = text.find(":", start + 8)
        sep2 = text.find("=\"", sep1 + 1) + 1
        end = text.find(quote, sep2 + 2)
        text = text[:start] + text[end + 1:]

with open(target, "w") as f:
    for line in text.split("\n"):
        keep = False
        for c in line:
            if c not in (" ", "\n"):
                keep = True
                break
        if keep:
            f.write(line + "\n")

print("File was saved sucessfully!")

How could it be improved?

\$\endgroup\$
1
  • \$\begingroup\$ You might find svgminify.com handy. \$\endgroup\$
    – chicks
    Apr 12, 2022 at 22:17

1 Answer 1

5
\$\begingroup\$

SVG is written in XML. As a rule, you should prefer using proper XML tools to process XML rather than doing ad hoc text substitutions, for robustness and maintainability. Look into using XSL Transforms instead.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.