Program za izračun geometrijskih karakteristik poligonalnih prerezov. Izdelava programa za izpis pogovorno vnešenih podatkov v različne zapise (TXT, XML, JSON, SQLite).
Povezave:
#! /usr/bin/env python
import sys
import xml.etree.cElementTree as et
import sqlite3
import json
def izpis_v_txt_datoteko(n, x, y):
print("Izpis v TXT ...")
dat = open(sys.argv[1] + ".txt", "w")
dat.write("{}\n".format(n))
for i in range(n):
dat.write("{} {}\n".format(x[i], y[i]))
dat.close()
def izpis_v_xml_datoteko(n, x, y):
print("Izpis v XML ...")
xml_prerez = et.Element("prerez")
xml_tocke = et.SubElement(xml_prerez, "tocke")
for i in range(n):
xml_tocka = et.SubElement(xml_tocke, "tocka")
xml_tocka.set("id", str(i + 1))
xml_x = et.SubElement(xml_tocka, "x")
xml_x.text = str(x[i])
xml_y = et.SubElement(xml_tocka, "y")
xml_y.text = str(y[i])
xml_tree = et.ElementTree(xml_prerez)
xml_tree.write(sys.argv[1] + ".xml", encoding='utf-8', xml_declaration=True)
def izpis_v_json_datoteko(n, x, y):
print("Izpis v JSON ...")
data = {"n": n, "x": x[:len(x)-1], "y": y[:len(y)-1]}
with open(sys.argv[1] + ".json", "w") as dat:
json.dump(data, dat)
def izpis_v_sqlite_datoteko(n, x, y):
print("Izpis v SQLite ...")
# Ustvari SQLite bazo in določi tabelo
db = sqlite3.connect(sys.argv[1] + ".sqlite")
cursor = db.cursor()
sql_command = """
CREATE TABLE IF NOT EXISTS tocke (
id INTEGER PRIMARY KEY,
x DOUBLE,
y DOUBLE);"""
cursor.execute(sql_command)
db.commit()
# Odstrani vse zapise
sql_command = """ DELETE FROM tocke;"""
cursor.execute(sql_command)
db.commit()
for i in range(n):
# format_str = """INSERT INTO tocke (id, x, y) VALUES ("{id}", "{x_sql}", "{y_sql}");"""
# sql_command = format_str.format(id=i+1, x_sql=x[i], y_sql=y[i])
sql_command = """INSERT INTO tocke (id, x, y) VALUES ("{}", "{}", "{}");""".format(i+1, x[i], y[i])
cursor.execute(sql_command)
db.commit()
db.close()
def vnos_podatkov():
# Vnos podatkov
print("Vnos podatkov ...")
n = int(input("Podaj število točk: "))
x = []
y = []
for i in range(n):
vrstica = input("Točka {}: ".format(i+1))
besede = vrstica.split()
x.append(float(besede[0]))
y.append(float(besede[1]))
return n, x, y
def main():
# Vnos podatkov
n, x, y = vnos_podatkov()
# Izpis podatkov
izpis_v_txt_datoteko(n, x, y)
izpis_v_xml_datoteko(n, x, y)
izpis_v_json_datoteko(n, x, y)
izpis_v_sqlite_datoteko(n, x, y)
if __name__ == "__main__": main()
4
0 0
1 0
1 1
0 1
<?xml version="1.0" encoding="UTF-8"?>
<prerez>
<tocke>
<tocka id="1">
<x>0.0</x>
<y>0.0</y>
</tocka>
<tocka id="2">
<x>1.0</x>
<y>0.0</y>
</tocka>
<tocka id="3">
<x>1.0</x>
<y>1.0</y>
</tocka>
<tocka id="4">
<x>0.0</x>
<y>1.0</y>
</tocka>
</tocke>
</prerez>
{
"n": 4,
"x": [
0,
1,
1,
0
],
"y": [
0,
0,
1,
1
]
}