Kurs Python richtig lernen/Aufgabe 4: Vektor Kantone: Unterschied zwischen den Versionen
Zur Navigation springen
Zur Suche springen
Josh.x (Diskussion | Beiträge) Keine Bearbeitungszusammenfassung |
Josh.x (Diskussion | Beiträge) Keine Bearbeitungszusammenfassung |
||
| Zeile 2: | Zeile 2: | ||
* Mithilfe von Shapely die Fläche eines Polygons (Kantonsgrenzen) berechnen | * Mithilfe von Shapely die Fläche eines Polygons (Kantonsgrenzen) berechnen | ||
* Dictionary sortieren | * Dictionary sortieren | ||
Installation von dem Shapely-Module in Linux (Terminal): | |||
sudo apt-get install python-shapely | |||
== kantone.py == | == kantone.py == | ||
Version vom 19. September 2012, 14:02 Uhr
- Einlesen einer GeoJSON Datei (cantons.geojson, enthalten in Musterloesungen.zip)
- Mithilfe von Shapely die Fläche eines Polygons (Kantonsgrenzen) berechnen
- Dictionary sortieren
Installation von dem Shapely-Module in Linux (Terminal):
sudo apt-get install python-shapely
kantone.py
Erwartet als Parameter die GeoJSON Datei und gibt den Namen und die Fläche für jeden Kanton aus.
# -*- coding: utf-8 -*-
import json, os, sys
import shapely.geometry
def kantone(json_file):
fp = open(json_file)
fc = json.load(fp) # FeatureCollection lesen
kant_dict = {} # Resultat-Dictionnaire
for feat in fc['features']:
name = feat['properties']['Nom_abbr']
geom = shapely.geometry.asShape(feat['geometry'])
kant_dict[name] = geom.area / 1000000 # Fläche in km2
return kant_dict
def main():
if len(sys.argv) < 2:
# Wird ausgeführt wenn das Programm nicht korrekt aufgerufen wurde
print """kantone.py
Gibt Namen und Flaeche fuer jeden Kanton aus.
Funktionsweise:
python kantone.py geojson_file
"""
sys.exit()
# Programm ausführen, das heisst, etwas Nützliches machen
json_file = sys.argv[1]
if not os.path.exists(json_file):
print "Fehler. Datei '%s' existiert nicht."
sys.exit()
kant_dict = kantone(json_file)
# Dictionnaire ausgeben
print 'Kanton\tFlaeche [km2]'
for kanton in kant_dict:
print '%s\t%s' % (kanton, kant_dict[kanton])
# Und nun den Dictionnaire sortiert nach Fläche ausgeben
# (grosse Kantone zuerst)
print '' # Eine Leerzeile
print 'Kantone sortiert nach Flaeche (absteigend):'
print 'Kanton\tFlaeche [km2]'
for kanton in sorted(kant_dict, key=kant_dict.get, reverse=True):
print '%s\t%s' % (kanton, kant_dict[kanton])
if __name__ == '__main__':
main()