如何在真实多边形上变换多边形字符串

时间:2016-07-22 18:06:55

标签: python polygon

我需要一些真正的多边形支持。 今天我有一个字符串,我需要改变一种可以识别为多边形的格式。

我直接从SQL获取polygon:

的值

示例:

我这样读过:

string = "POLYGON ((-47.158846224312285 -21.349760242365733;-47.158943117468695 -21.349706412900805;-47.159778541623055 -21.349008036758804))"

我需要更改此格式

list = [(-47.158846224312285,  -21.349760242365733), (47.158943117468695 -21.349706412900805),  (-47.159778541623055, -21.349008036758804)]

知道怎么修改?

2 个答案:

答案 0 :(得分:2)

您可以尝试使用re module这样的正则表达式解析字符串:

import re

pat = re.compile(r'''(-*\d+\.\d+ -*\d+\.\d+);*''')
s = "POLYGON ((-47.158846224312285 -21.349760242365733;-47.158943117468695 -21.349706412900805;-47.159778541623055 -21.349008036758804))"

matches = pat.findall(s)
if matches:
    lst = [tuple(map(float, m.split())) for m in matches]
    print(lst)

输出:

[(-47.158846224312285, -21.349760242365733), (-47.158943117468695, -21.349706412900805), (-47.159778541623055, -21.349008036758804)]

答案 1 :(得分:0)

根据输入字符串的方式,这可能只是简单地使用一些字符串操作shellinabox 库和一些字符串操作。

import re
# create a regular expression to extract polygon coordinates
polygon_re = re.compile(r"^POLYGON \(\((.*)\)\)") 
input = "POLYGON ((-47.1 -21.3;-47.1 -21.3;-47.1 -21.3))"
polygon_match = polygon_re.match(input)

if polygon_match is not None:
    coords_str = polygon_match.groups()[0]

    # parse string of coordinates into a list of float pairs
    point_strs = coord_str.split(";")
    polygon = [[float(s) for s in p.split()] for p in coords_str.split(";")]