Last active
December 12, 2020 00:33
-
-
Save Jeremiah-England/12d9e87f480deecfc5a73fb1e86dc4fb to your computer and use it in GitHub Desktop.
Silly WKT parser for Polygons and Multipolygons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Just a silly little wkt parser I wrote because for a minute there | |
I thought invalid shapely MultiPolygons were missing the | |
`difference` method if loaded via the `shapely.wkt` module. Turns | |
out it was just a spelling error. :D | |
Not made to be easy to read, sorry. But I thought it was cool so | |
I made a gist out of it. | |
""" | |
from shapely.geometry import Polygon, MultiPolygon | |
class WKT: | |
types = {'POLYGON': Polygon, 'MULTIPOLYGON': MultiPolygon} | |
@classmethod | |
def loads(cls, wkt_str): | |
first_space_index = wkt_str.index(' ') | |
wkt_type = wkt_str[:first_space_index] | |
if wkt_type not in cls.types: | |
raise NotImplementedError(f'Cannot parse type {wkt_type}') | |
if cls.types[wkt_type] is Polygon: | |
return cls.parse_polygon(wkt_str) | |
if cls.types[wkt_type] is MultiPolygon: | |
return cls.parse_multipolygon(wkt_str) | |
@staticmethod | |
def parse_polygon(wkt_str): | |
return Polygon([[float(num_str) for num_str in coord_str.split(' ')] | |
for poly_coords in wkt_str.strip('POLYGON').strip().strip('((').strip('))').split('), (') | |
for coord_str in poly_coords.split(', ')]) | |
@staticmethod | |
def parse_multipolygon(wkt_str): | |
return MultiPolygon([Polygon([[float(num_str) for num_str in coord_str.split(' ')] | |
for poly_coords in poly_str.split('), (') | |
for coord_str in poly_coords.split(', ')]) | |
for poly_str in wkt_str.strip('MULTIPOLYGON').strip().strip('(((').strip(')))').split(')), ((')]) | |
# That's all folks! (I want a new line to render after the last python line, thanks.) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment