6

我有一个包含一些几何数据的WKT文件。

这是一个示例(折线):

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)"

我想要的是点的坐标。所以我做了以下事情:

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']

这些s2, s3, s4 and s5只是虚拟变量,用来展示这个解决方案是超越善恶的。

有没有更简洁的解决方案?

4

4 回答 4

11

老问题,但这里是使用 JSON 和geomet的替代方法,这是一个转换 GeoJSON <-> WKT 的小型 Python 库。

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)
于 2017-06-15T11:25:04.853 回答
5
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')]

您可以使用map(float, nums)或等效。如果你想要浮动而不是字符串。

于 2013-05-24T09:22:37.677 回答
2
from shapely import wkt
p1 = wkt.loads('POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))')
于 2021-08-04T08:43:49.437 回答
1

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

于 2013-10-30T10:28:15.473 回答