Skip to content

Instantly share code, notes, and snippets.

@l3kn
Last active May 3, 2019 22:16
Show Gist options
  • Save l3kn/434b310f52f98d9f656ca11867b238da to your computer and use it in GitHub Desktop.
Save l3kn/434b310f52f98d9f656ca11867b238da to your computer and use it in GitHub Desktop.
from xml.dom import minidom
root = minidom.parse("weave.svg")
joinCount = 0
lines = []
for l1 in root.getElementsByTagName("line"):
x1 = l1.attributes['x1'].value
y1 = l1.attributes['y1'].value
x2 = l1.attributes['x2'].value
y2 = l1.attributes['y2'].value
lines.append((x1, y1, x2, y2))
print(len(lines))
output = []
while len(lines):
# Start a random line
x1, y1, x2, y2 = lines.pop()
# Then try to grow it in both directions,
# until no other line fits on either end.
# Possible improvment: Check if reversing the target line makes it fit
found = True
while found:
found = False
for l2 in lines:
x1_, y1_, x2_, y2_ = l2
# It seems like the for loop doesn't mind
# if we delete from the list it's working on
if found:
break
if x2 == x1_ and y2 == y1_:
x2 = x2_
y2 = y2_
found = True
elif x1 == x2_ and y1 == y2_:
x1 = x1_
y1 = y1_
found = True
if found:
lines.remove(l2)
joinCount += 1
output.append((x1, y1, x2, y2))
print(len(output))
cn1 = root.childNodes[1]
for child in cn1.childNodes:
cn1.removeChild(child)
for line in output:
newline = root.createElement("line")
newline.setAttribute("class", "st0")
newline.setAttribute("x1", line[0])
newline.setAttribute("y1", line[1])
newline.setAttribute("x2", line[2])
newline.setAttribute("y2", line[3])
cn1.appendChild(newline)
print("Joined " + str(joinCount) + " lines.")
file = open("output.svg", 'w')
file.write(root.toxml())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment