Changing A Path Class Name In Svg Python
Solution 1:
Use LXML python module to parse the SVG file. Then you can access all of the nodes and attributes quickly and easily. I do this all the time for XML, HTML, and SVG. Brute force string parsing is almost never the right way to go especially when dealing with a well formed language syntax like XML, SVG, and CSS.
I'm typing on my phone so I can't provide you with any examples right now. However, rest assured that LXML is simple to use and gives you a robust solution; robust unlike any string parsing code that you hack together.
Using XPath, you can easily find all of the nodes and modify their attributes. In your case:
for node in doc.xpath ("//path"):
node.get ("class")
Solution 2:
There is probably a parser doing the job, but by using open
and re.sub
, you can do:
import re
defincrement_value_in_string (s, inc_value):
return re.sub('(?<=cls-)\d*',lambda m: str(inc_value+int(m.group(0))),s)
# note: '(?<=cls-)\d*' is slightly different than in my answer to your previous # question as the pattern is less restrictive# open your svg file and read
svg_file = open('path_to_your_file\file.svg','r')
svg_txt = svg_file.read()
# increment the value after cls- by 5
increment_value = 5
svg_txt_modif = increment_value_in_string (svg_txt, increment_value)
# write back to a svg file
file_modif_svg = open('path_to_your_file\file_modif.svg','wb')
file_modif_svg.write(svg_txt_modif)
file_modif_svg.close()
The file file_modif.svg
has the value incremented by 5 everytime digits are after the pattern 'cls-'
Post a Comment for "Changing A Path Class Name In Svg Python"