Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a WKT-file

Tags:

python

I have a WKT-file containing some geometric data.

Here a sample (a polyline):

s = "ST_GeomFromText( 'LINESTRING( 11.6614 48.0189, 11.6671 48.011, 11.6712 48.0051, 11.6747 48.0001, 11.6777 47.9956, 11.6795 47.9927)',4326)"

What I want is the coordinates of the points. So I did the following:

s2 = s.split("'")[1]
s3 = s2.split("(")[1]
s4 = s3.strip(' )')
s5 = s4.split(',')
print s5
['11.6614 48.0189',
 ' 11.6671 48.011',
 ' 11.6712 48.0051',
 ' 11.6747 48.0001',
 ' 11.6777 47.9956',
 ' 11.6795 47.9927']

the s2, s3, s4 and s5 are just dummy variables to showcase that this solution is beyond good and Evil.

Is there any more concise solution for this?

like image 248
Tengis Avatar asked May 24 '13 09:05

Tengis


People also ask

What is wkt format python?

The WKT format is a markup language to represent geometric 2D and 3D objects, such as points, lines, polygons, and so on. In the WKT format, a polygon is represented by the coordinates of each point of the polygon.

What is wkt map?

Well-known text (WKT) is a human readable representation for spatial objects like points, lines, or enclosed areas on a map.


4 Answers

Old question, but here is an alternative using JSON and geomet, a small Python library that converts GeoJSON <-> WKT.

from geomet import wkt
import json

#your WKT input:
ls = 'LINESTRING(2.379444 48.723333, 2.365278 48.720278, 2.2525 48.696111, 2.224167 48.69, 2.129167 48.652222, 2.093611 48.638056)'

#convert it to GeoJSON:
ls_json = wkt.loads(ls)

#from this point on, ls_json is storing your data in JSON format, 
#which you can access like a python dict:
point = ls_json['coordinates'][5][1]
# --> gives you 48.638056

#e.g. turn everything into a list:
arr = []
for point in a['coordinates']:
    arr.append(point)
print(arr)
like image 179
Ulu83 Avatar answered Oct 04 '22 09:10

Ulu83


import re
from pprint import pprint

s = "ST_GeomFromText( 'LINESTRING( 11.6614 48.0189, 11.6671 48.011, 11.6712 48.0051, 11.6747 48.0001, 11.6777 47.9956, 11.6795 47.9927)',4326)"

nums = re.findall(r'\d+(?:\.\d*)?', s.rpartition(',')[0])
coords = zip(*[iter(nums)] * 2)
pprint(coords)

[('11.6614', '48.0189'),
 ('11.6671', '48.011'),
 ('11.6712', '48.0051'),
 ('11.6747', '48.0001'),
 ('11.6777', '47.9956'),
 ('11.6795', '47.9927')]

You could utilise map(float, nums) or equiv. if you wanted floats instead of strings.

like image 41
Jon Clements Avatar answered Oct 04 '22 09:10

Jon Clements


from shapely import wkt
p1 = wkt.loads('POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))')
like image 29
Michele Piccolini Avatar answered Oct 04 '22 07:10

Michele Piccolini


you can try https://pypi.python.org/pypi/pygeoif which parses wkt or https://pypi.python.org/pypi/parsewkt

like image 32
cleder Avatar answered Oct 04 '22 07:10

cleder