Code-Struktur / Wie mache ich es richtig?

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Mr. R341
User
Beiträge: 46
Registriert: Dienstag 29. September 2020, 10:51

Hi.
Ich Programmiere jetzt schon eine kleine Weile in Python, aber gerade was die Struktur meines Codes angeht, hat sich seit dem Anfang nichts geändert.
Ich weiß z.B. nicht, wie man das ganze mit "main()" macht, wie man den Code schön schlank hält, wie man funktionsdefinitionen ineinander verschachtelt (main()?), damit nicht von Anfang an alles in den Speicher geladen werden, usw.

Hier habe ich mal mein aktuelles Projekt.

Code: Alles auswählen

import itertools

#Funktion um Datei hinzuzufügen und gegebenenfalls die Dateiendung hinzuzufügen
def import_file(input_file, output_file):
    if input_file[-4:].lower() != ".svg":
        input_file = input_file + ".svg"  
    else:
        pass
    text = open(input_file, "r")
    text_2 = []
    for line in text:
        stripped_line = line.strip()
        line_list = stripped_line.split()
        text_2.append(line_list)
    calculate_positions(text_2, output_file)

#Funktion um die Position der einzelnen Kreise anzupassen
def calculate_positions(text_2, output_file):
    abs_xpos = int(text_2[1][2])
    abs_ypos = int(text_2[1][3][:-1])
    for absolute_x in text_2:
        try: 
            if int(absolute_x[2][4:-1]) < abs_xpos:
                abs_xpos = int(absolute_x[2][4:-1])
            else:
                pass
        except:
            pass
    for absolute_y in text_2:
        try: 
            if int(absolute_y[3][4:-1]) < abs_ypos:
                abs_ypos = int(absolute_y[3][4:-1])
            else:
                pass
        except:
            pass
    abs_xpos -= int(text_2[5][4][3:-1])
    abs_ypos -= int(text_2[5][4][3:-1])
    for ypos in text_2:
        try:
            if ypos[3][0:4] == 'cy="':
                ypos1 = int(ypos[3][4:-1]) - abs_ypos
                ypos[3] = 'cy="' + str(ypos1) + '"'
        except:
            pass
    for xpos in text_2:
        try:
            if xpos[2][0:4] == 'cx="':
                xpos1 = int(xpos[2][4:-1]) - abs_xpos
                xpos[2] = 'cx="' + str(xpos1) + '"'
        except:
            pass
    calculate_size(text_2, output_file)

#Funktion um die Gesamtgröße der SVG anzupassen damit jede Seite Bündig ist
def calculate_size(text_2, output_file):
    height = int(text_2[5][4][3:-1])
    width = int(text_2[5][4][3:-1])
    for wide in text_2:
        try:
            if int(wide[2][4:-1]) > width:
                width = int(wide[2][4:-1])
            else:
                pass
        except:
            pass
    for high in text_2:
        try:
            if int(high[3][4:-1]) > height:
                height = int(high[3][4:-1])
            else:
                pass
        except:
            pass
    for high in text_2:
        try:
            if int(high[3][4:-1]) > height:
                height = int(high[3][4:-1])
            else:
                pass
        except:
            pass
    width  += int(text_2[5][4][3:-1])
    height += int(text_2[5][4][3:-1])
    text_2[1][2] = str(width)
    text_2[1][3] = str(height) + '"'
    text_2[2][1] = 'height="' + str(height) + '"'
    text_2[2][2] = 'width="' + str(width) + '"'
    make_list(text_2, output_file)

#Funktion um aus der Liste mit Listen wieder einzelne Strings zu machen
def make_list(text_2, output_file):
    text_2 =" ".join(list(itertools.chain.from_iterable(text_2)))
    text_2 = text_2.replace("> <", ">\n<")
    write_to_file(text_2, output_file)

#Funktion um die neuen Strings in eine neue Datei zu schreiben
def write_to_file(text_2, output_file):
    if output_file[-4:].lower() != ".svg":
        output_file = output_file + ".svg"  
    else:
        pass
    file = open(output_file, "w")
    file.write(text_2)
    file.close()

#Abfrage der Dateipfade und -namen
input_file = input('Path to Input file:\n("C:/Path/to/file.svg") ')
input_file = input_file.replace('"', '')
input_file = input_file.replace("'", '')
output_file = input('Path to Output file:\n("C:/Path/to/file.svg") ')
output_file = output_file.replace('"', '')
output_file = output_file.replace("'", '')

#Aufruf der Hauptdunktion
import_file(input_file, output_file)
eine .svg zum testen:

Code: Alles auswählen

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
	 viewBox="0 0 2000 3000" xml:space="preserve" background-color="black" >
    <rect height="3000" width="2000" fill="black"/>
<circle id="circle" cx="450" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="500" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="550" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="550" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="600" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="600" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="650" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="650" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="650" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="650" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="700" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="700" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="700" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="750" cy="1180" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="750" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="750" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="750" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="750" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="800" cy="1094" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="800" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="800" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="800" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="800" cy="921" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="850" cy="1180" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="850" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="850" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="850" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="850" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="850" cy="836" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="900" cy="1094" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="900" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="900" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="900" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="900" cy="577" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="900" cy="750" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="900" cy="921" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="950" cy="1180" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="950" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="950" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="950" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="950" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="950" cy="491" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="950" cy="836" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1000" cy="1094" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1000" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1000" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1000" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1000" cy="404" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1000" cy="577" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1000" cy="750" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1000" cy="921" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1050" cy="1180" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1050" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1050" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1050" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1050" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1050" cy="491" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1050" cy="836" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1100" cy="1094" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1100" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1100" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1100" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1100" cy="577" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1100" cy="750" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1100" cy="921" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1150" cy="1180" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1150" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1150" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1150" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1150" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1150" cy="836" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1200" cy="1094" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1200" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1200" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1200" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1200" cy="921" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1250" cy="1180" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1250" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1250" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1250" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1250" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1300" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1300" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1300" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1350" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1350" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1350" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1350" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1400" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1400" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1450" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1450" cy="1869" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1500" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="1550" cy="1869" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle" cx="300" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="350" cy="1868" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="400" cy="1782" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="400" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="450" cy="1696" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="500" cy="1438" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="500" cy="1610" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="500" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="550" cy="1352" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="550" cy="1524" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="600" cy="1266" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="600" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="650" cy="1008" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="650" cy="1180" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="700" cy="1094" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="700" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="700" cy="921" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="750" cy="663" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="750" cy="836" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="800" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="800" cy="577" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="800" cy="750" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="850" cy="491" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="900" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="900" cy="404" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="950" cy="318" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1000" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1050" cy="318" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1100" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1100" cy="404" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1150" cy="491" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1200" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1200" cy="577" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1200" cy="750" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1250" cy="663" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1250" cy="836" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1300" cy="1094" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1300" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1300" cy="921" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1350" cy="1008" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1350" cy="1180" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1400" cy="1266" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1400" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1450" cy="1352" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1450" cy="1524" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1500" cy="1438" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1500" cy="1610" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1500" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1550" cy="1696" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1600" cy="1782" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1600" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1650" cy="1869" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="1700" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle" cx="600" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="700" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="750" cy="1008" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="800" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="850" cy="1008" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="850" cy="663" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="900" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="950" cy="1008" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="950" cy="663" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="1000" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="1000" cy="232" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="1050" cy="1008" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="1050" cy="663" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="1100" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="1150" cy="1008" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="1150" cy="663" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="1200" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="1250" cy="1008" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="1300" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="1400" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle" cx="950" cy="2041" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle" cx="950" cy="2141" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle" cx="950" cy="2241" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle" cx="950" cy="2341" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle" cx="1050" cy="2041" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle" cx="1050" cy="2141" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle" cx="1050" cy="2241" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle" cx="1050" cy="2341" r="50" opacity="1" fill="rgb(210,180,140)"/>
</svg>
Sorry, wenn der svg-Code nicht richtig dargestellt wird.. einfach in ne Textdatei packen und als SVG speichern...
Benutzeravatar
__blackjack__
User
Beiträge: 14005
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@Mr. R341: Als erstes mal solltest Du die ganzen sinnlosen ``else: pass`` entfernen.

Und als nächstes dann die ganzen ``try:``/``except: pass`` Blöcke.

SVG ist XML, das mit Zeichenkettenoperationen zu bearbeiten ist falsch. Das macht man mit einem XML-Parser. `xml.ElementTree` aus der Standardbibliothek oder `lxml`.

Damit ändert sich letztlich das so ziemlich das gesamte Programm, so dass man das gleich von Grund auf neu schreiben kann.

Das gezeigte XML hat in jedem <circle>-Element die gleiche `id` — das ist falsch, IDs müssen dokumentweit eindeutig sein.

Auf Modulebene sollte nur Code stehen der Konstanten, Funktionen, und Klassen definiert. Das Hauptprogramm steht üblicherweise in einer Funktion die `main()` heisst.
“The best book on programming for the layman is »Alice in Wonderland«; but that's because it's the best book on anything for the layman.” — Alan J. Perlis
Sirius3
User
Beiträge: 18253
Registriert: Sonntag 21. Oktober 2012, 17:20

`main` ist eine Funktion, wie jede andere auch, nur dass es halt die erste ist, die aufgerufen wird.
Apropos Funktionen: Funktionen haben genau eine Aufgabe und kehren dann zum Aufrufer zurück. Deine Funktionen sind aber seltsam verkettet, die eine ruft die nächste auf. Das macht den Programmablauf sehr undurchsichtig.

Zum Beispiel `import_file` sollte nicht auch noch output_file brauchen, weil die Funktion sollte genau das machen, was sie sagt, etwas importieren.

Code: Alles auswählen

def main():
    input_file = input('Path to Input file:\n("C:/Path/to/file.svg") ')
    output_file = input('Path to Output file:\n("C:/Path/to/file.svg") ')

    #Aufruf der Hauptdunktion
    svg_data = import_file(input_file)
    calculate_positions(svg_data)
    calculate_size(svg_data)
    svg_data = make_list(svg_data)
    write_to_file(svg_data, output_file)

if __name__ == '__main__':
    main()
Die ganzen `else: pass` Blöcke sind überflüssig, da Du ja im else-Block nichts machst.
Nakte excepts schreibt man auch nicht, weil die jeden Fehler auch viele Programmierfehler abfangen. Bei Deinem Code versteh ich auch nicht, welchen Fehler Du dort sinnvollerweise überhaupt abfangen willst.
Listen verändert man in Python nicht, sondern erzeugt neue.
Und last but not least, SVG ist ein XML-Format und XML verarbeitet man nicht mit String-Funktionen, sondern benutzt einen XML-Parser.
Benutzeravatar
pillmuncher
User
Beiträge: 1529
Registriert: Samstag 21. März 2009, 22:59
Wohnort: Pfaffenwinkel

Nackte except-Klauseln sind immer verkehrt, weil so auch Programmierfehler abgefangen werden, die man eigentlich sehen möchte.

else-Klauseln die nichts außer einem pass-Statement beinhalten, sind sinnlos.

If bla: pass else: pass ist doppelt sinnlos.

Magic Numbers sind böse. Statt Felder über fest kodierte Indizes anzusprechen, verwende sinnvolle Datenstrukturen. ZB. ein dict.

Statt über eine Liste zu iterieren und Maximalwerte durch Vergleiche zu errechnen, vberwende die max()-Funktion.
In specifications, Murphy's Law supersedes Ohm's.
Mr. R341
User
Beiträge: 46
Registriert: Dienstag 29. September 2020, 10:51

@__blackjack__

Danke für deine Antwort.

Das mit den ID's hab ich noch nicht gemacht, das stimmt...
Das else: pass verstehe ich auch, warum das raus kann...
Aber try, except, pass muss ich drin haben, da sonst der Fehler den Code stoppt, weil nicht jede liste die erstellt wird den jeweiligen Index vergeben hat..

Kannst du mir hierfür ein Beispiel geben wie ich das in die main() schreibe?

ich habe schoneinmal gesehen, dass es dashier gibt:

Code: Alles auswählen

def main():
    print("Hello World!")

if __name__ == "__main__":
    main()
Aber Anfangen kann ich damit nichts... was ist __name__? was ist __main__? Und warum wird nicht einfach gleich "main()" aufgrufen? warum erst ein if-statement?
Und wie wäre das am oberen Beispiel anzuwenden?
Musst mir jetzt nicht alles umschreiben, was du beschrieben hast, aber wenn du das mit dem main() mit dem gesammten Code anwenden könntest, wäre das super nett, damit ich verstehe, wie man es macht
Mr. R341
User
Beiträge: 46
Registriert: Dienstag 29. September 2020, 10:51

pillmuncher hat geschrieben: Montag 16. November 2020, 22:23 Nackte except-Klauseln sind immer verkehrt, weil so auch Programmierfehler abgefangen werden, die man eigentlich sehen möchte.

else-Klauseln die nichts außer einem pass-Statement beinhalten, sind sinnlos.

If bla: pass else: pass ist doppelt sinnlos.

Magic Numbers sind böse. Statt Felder über fest kodierte Indizes anzusprechen, verwende sinnvolle Datenstrukturen. ZB. ein dict.

Statt über eine Liste zu iterieren und Maximalwerte durch Vergleiche zu errechnen, vberwende die max()-Funktion.
else: pass hab ich schon raus genommen..
und except: pass hab ich erst reingemacht, nachdem ich die Fehler die kommen gesehen habe..

aber wie bekomme ich rohen xml-text in eine solche "Sinnvolle" Datenstruktur?

Wie würde ich die max() dunktion in meinem Beispiel anwenden? reicht, wenn du dir nur eine Funktion rauspickst...
Benutzeravatar
__blackjack__
User
Beiträge: 14005
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@Mr. R341: Die ``try``/``except: pass`` müssen da raus. Vielleicht müsste man die durch etwas anderes ersetzen, zum Beispiel Code der nicht zu Ausnahmen führt. Generell wichtig hier für Dich: keine ”nackten” ``except`` ohne konkrete Ausnahme. Und konkret muss das ja eh alles weg weil man XML nicht mit Zeichenkettenoperationen verarbeitet.

__name__ ist ein Variablenname. "__main__" ist eine Zeichenkette mit eben diesem Inhalt den man da sieht. Und das `__name__` den Namen des Moduls enthält, ausser wenn das Modul als Programm ausgeführt wird, hätte man in der Dokumentation nachlesen können. Dazu ist die da. Wenn man das Modul als Programm ausführt, dann hat `__name__` den Wert "__main__".
“The best book on programming for the layman is »Alice in Wonderland«; but that's because it's the best book on anything for the layman.” — Alan J. Perlis
Benutzeravatar
pillmuncher
User
Beiträge: 1529
Registriert: Samstag 21. März 2009, 22:59
Wohnort: Pfaffenwinkel

Funktionen, die nur als Zwischenschritte einer Berechnung verwendet werden und die alle am Ende den nächsten Schritt (d.h. die nächste Funtion) aufrufen, sind schlecht. Funktionen sind nicht benannte Codeblöcke, sondern wiederverwendbare abgeschlossene Einheiten. Wie willst du eine Funktion wiederverwenden, wenn sie den gesamten Ablaufplan für deinen momentanen, spezifischen Anwendungsfall beinhaltet?
In specifications, Murphy's Law supersedes Ohm's.
Mr. R341
User
Beiträge: 46
Registriert: Dienstag 29. September 2020, 10:51

Sirius3 hat geschrieben: Montag 16. November 2020, 22:14 `main` ist eine Funktion, wie jede andere auch, nur dass es halt die erste ist, die aufgerufen wird.
Apropos Funktionen: Funktionen haben genau eine Aufgabe und kehren dann zum Aufrufer zurück. Deine Funktionen sind aber seltsam verkettet, die eine ruft die nächste auf. Das macht den Programmablauf sehr undurchsichtig.

Zum Beispiel `import_file` sollte nicht auch noch output_file brauchen, weil die Funktion sollte genau das machen, was sie sagt, etwas importieren.

Code: Alles auswählen

def main():
    input_file = input('Path to Input file:\n("C:/Path/to/file.svg") ')
    output_file = input('Path to Output file:\n("C:/Path/to/file.svg") ')

    #Aufruf der Hauptdunktion
    svg_data = import_file(input_file)
    calculate_positions(svg_data)
    calculate_size(svg_data)
    svg_data = make_list(svg_data)
    write_to_file(svg_data, output_file)

if __name__ == '__main__':
    main()
Die ganzen `else: pass` Blöcke sind überflüssig, da Du ja im else-Block nichts machst.
Nakte excepts schreibt man auch nicht, weil die jeden Fehler auch viele Programmierfehler abfangen. Bei Deinem Code versteh ich auch nicht, welchen Fehler Du dort sinnvollerweise überhaupt abfangen willst.
Listen verändert man in Python nicht, sondern erzeugt neue.
Und last but not least, SVG ist ein XML-Format und XML verarbeitet man nicht mit String-Funktionen, sondern benutzt einen XML-Parser.
Wow @Sirius3 :D Von dir bin ich es garnicht anders gewohnt ^^ vielen vielen Dank ♥
und Indentation-Mäßig?
sind die ganzen anderen Funktionen dann am Anfang? oder sind sie in die main() eingerückt? 1 oder 2?

1:

Code: Alles auswählen


def main():
	do something_1()
	
	
	def something_1():
		print("Hello World!")

if __name__ == '__main__':
    main()
2:

Code: Alles auswählen


def main():
	do something_1()
	
	
def something_1():
	print("Hello World!")

if __name__ == '__main__':
    main()
und: spielt es eine Rolle, welchen standort die definitionen haben? oder muss/sollte "main()" immer an oberster Stelle definiert werden?


Und auch an dich die Frage:

warum "if __name__ == '__main__' "?

Edit:
Okay... das mit der Einrückung war doof zu fragen sorry :P

Auch danke an __blackjack__ für die Erklärung
Benutzeravatar
pillmuncher
User
Beiträge: 1529
Registriert: Samstag 21. März 2009, 22:59
Wohnort: Pfaffenwinkel

if __name__ = '__main__': main() verwendet man, damit man das Modul importieren kann, ohne dass main() ausgeführt wird. __name__ == '__main__', wenn das Modul direkt aufgerufen wird, also mit $ python3 das_modul.py.
In specifications, Murphy's Law supersedes Ohm's.
Mr. R341
User
Beiträge: 46
Registriert: Dienstag 29. September 2020, 10:51

pillmuncher hat geschrieben: Montag 16. November 2020, 22:50 if __name__ = '__main__': main() verwendet man, damit man das Modul importieren kann, ohne dass main() ausgeführt wird. __name__ == '__main__', wenn das Modul direkt aufgerufen wird, also mit $ python3 das_modul.py.
Aber was ist der Unterschied?
Benutzeravatar
pillmuncher
User
Beiträge: 1529
Registriert: Samstag 21. März 2009, 22:59
Wohnort: Pfaffenwinkel

Programmiere nach dem EVA-Prinzip (Eingabe, Verarbeitung, Ausgabe), vermeide Wiederholungen im Code und verwende dafür Hilfsfunktionen:

Code: Alles auswählen

def cleanup_filename(filename)
    filename = filename.replace('"', '').replace("'", '')
    if filename.lower().endswith('.svg'):
        return filename
    else:
        return filename + '.svg'


def ectract_data(some_file):
    # do the extracting here:
    return ...


def transmogrify(data):
    # do the transmogrification here
    return ...


ASK_IN_FILENAME = 'Path to Input File:\n("C:/Path/to/file.svg") '
ASK_OUT_FILENAME = 'Path to Output File:\n("C:/Path/to/file.svg") '


def main():
    with open(cleanup_filename(input(ASK_IN_FILENAME)), 'r') as in_file:
        with open(cleanup_filename(input(ASK_OUT_FILENAME)), 'w') as out_file:
            out_file.write(transmogrify(extract_data(in_file)))


if name__ == '__main__':
    main()
In specifications, Murphy's Law supersedes Ohm's.
Benutzeravatar
pillmuncher
User
Beiträge: 1529
Registriert: Samstag 21. März 2009, 22:59
Wohnort: Pfaffenwinkel

Der Unterschied ist, dass man manchmal Funktionen aus dem Modul aus einem anderen Programm heraus aufrufen will, ohne dass das Module selbst als Programm ausgeführt wird.
In specifications, Murphy's Law supersedes Ohm's.
Mr. R341
User
Beiträge: 46
Registriert: Dienstag 29. September 2020, 10:51

pillmuncher hat geschrieben: Montag 16. November 2020, 23:02 Der Unterschied ist, dass man manchmal Funktionen aus dem Modul aus einem anderen Programm heraus aufrufen will, ohne dass das Module selbst als Programm ausgeführt wird.
Mit Module meinst du definitionen?
Benutzeravatar
pillmuncher
User
Beiträge: 1529
Registriert: Samstag 21. März 2009, 22:59
Wohnort: Pfaffenwinkel

Nein. Ein Modul ist üblicherweise einfach eine Python-Datei.
In specifications, Murphy's Law supersedes Ohm's.
Mr. R341
User
Beiträge: 46
Registriert: Dienstag 29. September 2020, 10:51

@all ich setzte mich jetzt nochmals ran und werde in naher Zukunft den Code erneut zeigen.. danach sind eue Meinungen gefragt ^^

Was ich bis jetzt habe:

Code: Alles auswählen

import itertools
import xml.etree.ElementTree as ET

svg_link = "{http://www.w3.org/2000/svg}"

def main():
    input_file = input('Path to Input file:\n("C:/Path/to/file.svg") ')
    input_file = input_file.replace('"', '')
    input_file = input_file.replace("'", '')
    svg_data = import_file(input_file)
    global tree
    tree = ET.parse(svg_data)
    global root
    root = tree.getroot()
#    for child in root.findall(".//{http://www.w3.org/2000/svg}circle"):
#        print(child.attrib['fill'])

#Funktion um Datei hinzuzufügen und gegebenenfalls die Dateiendung hinzuzufügen
def import_file(input_file):
    if input_file[-4:].lower() != ".svg":
        input_file = input_file + ".svg"  
    return input_file


#    output_file = input('Path to Output file:\n("C:/Path/to/file.svg") ')
#    output_file = output_file.replace('"', '')
#    output_file = output_file.replace("'", '')

    #Aufruf der Hauptdunktion
#    
    calculate_positions()
#    calculate_size(svg_data)
#    svg_data = make_list(svg_data)
#    write_to_file(svg_data, output_file)

#Funktion um die Position der einzelnen Kreise anzupassen
def calculate_positions():
    size = root.attrib['viewBox'].split()
    abs_xpos = size[2]
    abs_ypos = size[3]
    for absolute_x in root.findall(".//{http://www.w3.org/2000/svg}circle"):
        try: 
            if absolute_x.attrib['cx'] < abs_xpos:
                abs_xpos = absolute_x['cx']
    for absolute_y in svg_data:
        try: 
            if absolute_y.attrib['cy'] < abs_ypos:
                abs_ypos = absolute_y.attrib['cy']
Benutzeravatar
pillmuncher
User
Beiträge: 1529
Registriert: Samstag 21. März 2009, 22:59
Wohnort: Pfaffenwinkel

global hat in einem ordentlichen Programm nichts zu suchen. Wenn du in einer Funktion einen Wert benötigst, übergib ihn als Argument.
In specifications, Murphy's Law supersedes Ohm's.
Mr. R341
User
Beiträge: 46
Registriert: Dienstag 29. September 2020, 10:51

Here it is... Kein try/except, keine Error, alles in der main(), keine Zeichenkettenoperationen, sondern eine "sinnvolle" Datenstruktur :P und keine globale variablen...

Was haltet ihr davon?

Code: Alles auswählen

import xml.etree.ElementTree as ET

def main():
    ET.register_namespace('', "http://www.w3.org/2000/svg")
    input_file = input('Path to Input file:\n("C:/Path/to/file.svg") ')
    input_file = input_file.replace('"', '')
    input_file = input_file.replace("'", '')
    output_file = input('Path to Output file:\n("C:/Path/to/file.svg") ')
    output_file = output_file.replace('"', '')
    output_file = output_file.replace("'", '')
    svg_data = import_file(input_file)
    tree = ET.parse(svg_data)
    root = tree.getroot()
    size = root.attrib['viewBox'].split()
    svg_link = "{http://www.w3.org/2000/svg}"
    calculate_positions(root, size, svg_link)
    calculate_size(root, size, svg_link)
    write_to_file(root, tree, output_file, size)

#Funktion um Datei hinzuzufügen und gegebenenfalls die Dateiendung hinzuzufügen
def import_file(input_file):
    if input_file[-4:].lower() != ".svg":
        input_file = input_file + ".svg"  
    return input_file

#Funktion um die Position der einzelnen Kreise anzupassen
def calculate_positions(root, size, svg_link):
    abs_xpos = int(size[2])
    abs_ypos = int(size[3])
    
    for absolute_x in root.findall(".//" + svg_link + "circle"):
        if int(absolute_x.attrib['cx']) < abs_xpos:
            abs_xpos = int(absolute_x.attrib['cx']) - int(absolute_x.attrib['r'])
    for absolute_y in root.findall(".//" + svg_link + "circle"):
        if int(absolute_y.attrib['cy']) < abs_ypos:
            abs_ypos = int(absolute_y.attrib['cy']) - int(absolute_y.attrib['r'])
    for ypos in root.findall(".//" + svg_link + "circle"):
        ypos.attrib['cy'] = str(int(ypos.attrib['cy']) - abs_ypos)
    for xpos in root.findall(".//" + svg_link + "circle"):
        xpos.attrib['cx'] = str(int(xpos.attrib['cx']) - abs_xpos)
    return root, size

#Funktion um die Gesamtgröße der SVG anzupassen damit jede Seite Bündig ist
def calculate_size(root, size, svg_link):
    height = 0
    width = 0
    for wide in root.findall(".//" + svg_link + "circle"):
        if int(wide.attrib['cx']) > width:
            width = int(wide.attrib['cx'])     
    for high in root.findall(".//" + svg_link + "circle"):
        if int(high.attrib['cy']) > height:
            height = int(wide.attrib['cy'])
    for rect in root.findall(".//" + svg_link + "rect"):
        rect.attrib["height"] = str(height + int(wide.attrib['r']))
        rect.attrib["width"] = str(width + int(wide.attrib['r']))
    size[2] = str(width + int(wide.attrib['r']))
    size[3] = str(height + int(wide.attrib['r']))
    return root, size

#Funktion um die neuen Strings in eine neue Datei zu schreiben
def write_to_file(root, tree, output_file, size):
    root.attrib['viewBox'] =" ".join(size)
    if output_file[-4:].lower() != ".svg":
        output_file = output_file + ".svg"
    tree.write(output_file)

#Aufruf der Hauptfunktion
if __name__ == '__main__':
    main()
Und hier die Input-File:

Code: Alles auswählen

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
	 viewBox="0 0 2000 3000" xml:space="preserve">
<rect   id="rectangle001" height="3000" width="2000" fill="black"/>
<circle id="circle001" cx="450" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle002" cx="500" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle003" cx="550" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle004" cx="550" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle005" cx="600" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle006" cx="600" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle007" cx="650" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle008" cx="650" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle009" cx="650" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle010" cx="650" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle011" cx="700" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle012" cx="700" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle013" cx="700" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle014" cx="750" cy="1180" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle015" cx="750" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle016" cx="750" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle017" cx="750" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle018" cx="750" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle019" cx="800" cy="1094" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle020" cx="800" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle021" cx="800" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle022" cx="800" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle023" cx="800" cy="921" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle024" cx="850" cy="1180" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle025" cx="850" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle026" cx="850" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle027" cx="850" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle028" cx="850" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle029" cx="850" cy="836" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle030" cx="900" cy="1094" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle031" cx="900" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle032" cx="900" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle033" cx="900" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle034" cx="900" cy="577" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle035" cx="900" cy="750" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle036" cx="900" cy="921" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle037" cx="950" cy="1180" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle038" cx="950" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle039" cx="950" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle040" cx="950" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle041" cx="950" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle042" cx="950" cy="491" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle043" cx="950" cy="836" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle044" cx="1000" cy="1094" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle045" cx="1000" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle046" cx="1000" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle047" cx="1000" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle048" cx="1000" cy="404" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle049" cx="1000" cy="577" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle050" cx="1000" cy="750" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle051" cx="1000" cy="921" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle052" cx="1050" cy="1180" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle053" cx="1050" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle054" cx="1050" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle055" cx="1050" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle056" cx="1050" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle057" cx="1050" cy="491" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle058" cx="1050" cy="836" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle059" cx="1100" cy="1094" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle060" cx="1100" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle061" cx="1100" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle062" cx="1100" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle063" cx="1100" cy="577" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle064" cx="1100" cy="750" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle065" cx="1100" cy="921" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle066" cx="1150" cy="1180" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle067" cx="1150" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle068" cx="1150" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle069" cx="1150" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle070" cx="1150" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle071" cx="1150" cy="836" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle072" cx="1200" cy="1094" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle073" cx="1200" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle074" cx="1200" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle075" cx="1200" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle076" cx="1200" cy="921" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle077" cx="1250" cy="1180" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle078" cx="1250" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle079" cx="1250" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle080" cx="1250" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle081" cx="1250" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle082" cx="1300" cy="1266" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle083" cx="1300" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle084" cx="1300" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle085" cx="1350" cy="1352" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle086" cx="1350" cy="1524" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle087" cx="1350" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle088" cx="1350" cy="1868" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle089" cx="1400" cy="1610" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle090" cx="1400" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle091" cx="1450" cy="1696" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle092" cx="1450" cy="1869" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle093" cx="1500" cy="1782" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle094" cx="1550" cy="1869" r="50" opacity="1" fill="rgb(0,255,0)"/>
<circle id="circle095" cx="300" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle096" cx="350" cy="1868" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle097" cx="400" cy="1782" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle098" cx="400" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle099" cx="450" cy="1696" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle100" cx="500" cy="1438" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle101" cx="500" cy="1610" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle102" cx="500" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle103" cx="550" cy="1352" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle104" cx="550" cy="1524" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle105" cx="600" cy="1266" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle106" cx="600" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle107" cx="650" cy="1008" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle108" cx="650" cy="1180" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle109" cx="700" cy="1094" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle100" cx="700" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle111" cx="700" cy="921" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle112" cx="750" cy="663" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle113" cx="750" cy="836" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle114" cx="800" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle115" cx="800" cy="577" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle116" cx="800" cy="750" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle117" cx="850" cy="491" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle118" cx="900" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle119" cx="900" cy="404" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle120" cx="950" cy="318" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle121" cx="1000" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle122" cx="1050" cy="318" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle123" cx="1100" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle124" cx="1100" cy="404" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle125" cx="1150" cy="491" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle126" cx="1200" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle127" cx="1200" cy="577" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle128" cx="1200" cy="750" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle129" cx="1250" cy="663" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle130" cx="1250" cy="836" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle131" cx="1300" cy="1094" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle132" cx="1300" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle133" cx="1300" cy="921" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle134" cx="1350" cy="1008" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle135" cx="1350" cy="1180" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle136" cx="1400" cy="1266" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle137" cx="1400" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle138" cx="1450" cy="1352" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle139" cx="1450" cy="1524" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle140" cx="1500" cy="1438" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle141" cx="1500" cy="1610" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle142" cx="1500" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle143" cx="1550" cy="1696" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle144" cx="1600" cy="1782" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle145" cx="1600" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle146" cx="1650" cy="1869" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle147" cx="1700" cy="1955" r="50" opacity="1" fill="rgb(255,0,0)"/>
<circle id="circle148" cx="600" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle149" cx="700" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle150" cx="750" cy="1008" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle151" cx="800" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle152" cx="850" cy="1008" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle153" cx="850" cy="663" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle154" cx="900" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle155" cx="950" cy="1008" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle156" cx="950" cy="663" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle157" cx="1000" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle158" cx="1000" cy="232" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle159" cx="1050" cy="1008" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle160" cx="1050" cy="663" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle161" cx="1100" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle162" cx="1150" cy="1008" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle163" cx="1150" cy="663" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle164" cx="1200" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle165" cx="1250" cy="1008" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle166" cx="1300" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle167" cx="1400" cy="1438" r="50" opacity="1" fill="rgb(255,255,0)"/>
<circle id="circle168" cx="950" cy="2041" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle169" cx="950" cy="2141" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle170" cx="950" cy="2241" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle171" cx="950" cy="2341" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle172" cx="1050" cy="2041" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle173" cx="1050" cy="2141" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle174" cx="1050" cy="2241" r="50" opacity="1" fill="rgb(210,180,140)"/>
<circle id="circle175" cx="1050" cy="2341" r="50" opacity="1" fill="rgb(210,180,140)"/>
</svg>
Sirius3
User
Beiträge: 18253
Registriert: Sonntag 21. Oktober 2012, 17:20

Die Kommentare vor den Funktionen sind ungewöhnlich formuliert, um nicht zu sagen, irreführend.
`import_file` importiert weder eine Datei, wie der Funktionsname vermuten läßt, noch fügt es irgendwo eine Datei hinzu, wie es der Kommentar behauptet.
`svg_link` sollte eine Konstante sein, damit muß man sie nicht überall als Argument übergeben.
Strings setzt man nicht mit + zusammen, sondern benutzt FormatStrings.
svg_data ist eine Dateiname und keine SVG-Daten. Die Funktion import_file ist damit eigentlich überflüssig.
Dass bei der Eingabe irgendwelche Anführungszeichen gelöscht werden, ist überraschend für den Anwender, gehört also weg.
Du benutzt die Rückgabewerte der Funktionen gar nicht. Leider sind Listen veränderlich, so dass Du den Fehler gar nicht bemerkst.
In den calculat_-Funktionen bindest Du die for-Schleifen-Werte an komische Namen, denn es handelt sich immer um circle-Elemente und nie um einen x- oder y-Wert oder eine Breite oder eine Höhe. Schlechte Namen sind sehr verwirrend, weil man nichts versteht, oder Bahnhof auf dem Tisch ist grün weiter als schnell.
Sirius3
User
Beiträge: 18253
Registriert: Sonntag 21. Oktober 2012, 17:20

So könnte das aussehen:

Code: Alles auswählen

import xml.etree.ElementTree as ET

SVG_LINK = "{http://www.w3.org/2000/svg}"
ET.register_namespace('', SVG_LINK)

def adjust_positions(root, width, height):
    """ Funktion um die Position der einzelnen Kreise anzupassen """
    abs_xpos = width
    abs_ypos = height
    for circle in root.findall(f".//{SVG_LINK}circle"):
        r = int(circle.attrib['r'])
        cx = int(circle.attrib['cx'])
        if cx - r < abs_xpos:
            abs_xpos = cx - r
        cy = int(circle.attrib['cy'])
        if cy - r< abs_ypos:
            abs_ypos = cy - r
    for circle in root.findall(f".//{SVG_LINK}circle"):
        circle.attrib['cy'] = str(int(circle.attrib['cy']) - abs_ypos)
        circle.attrib['cx'] = str(int(circle.attrib['cx']) - abs_xpos)

def calculate_size(root):
    """ Funktion um die Gesamtgröße der SVG anzupassen damit jede Seite Bündig ist """
    height = 0
    width = 0
    for circle in root.findall(f".//{SVG_LINK}circle"):
        cx = int(circle.attrib['cx'])
        cy = int(circle.attrib['cy'])
        r = int(circle.attrib['r'])
        if cx > width:
            width = cx
        if cy > height:
            height = cy
    # warum wird hier der Radius des letzten Kreises verwendet
    return width + r, height + r


def input_svg_filename(type):
    filename = input(f'Path to {type} file:\n("C:/Path/to/file.svg") ')
    if not filename.endswith('.svg'):
        filename += ".svg"
    return filename


def main():
    input_filename = input_svg_filename("Input")
    output_filename = input_svg_filename("Output")
    tree = ET.parse(input_file)
    root = tree.getroot()
    size = list(map(int, root.attrib['viewBox'].split()))
    width, height = size[2:4]
    adjust_positions(root, width, height)
    width, height = calculate_size(root)
    size = [0, 0, width, height]
    for rect in root.findall(f".//{SVG_LINK}rect"):
        rect.attrib["height"] = str(height)
        rect.attrib["width"] = str(width)
    root.attrib['viewBox'] =" ".join(map(str, size))
    tree.write(output_file)
    write_to_file(tree, output_file)


if __name__ == '__main__':
    main()
Ein paar Bugs habe ich sozusagen aus Versehen beim Umschreiben schon korrigert, weil sie sozusagen durch die Verwendung sinnvoller Variablennamen offensichtlich waren. Andere habe ich mit einem Kommentar versehen.
Antworten