如何将wkt形式的多边形列表转换为多多边形?

时间:2019-04-23 00:22:45

标签: python polygon shapely

我有一个多边形列表,其中每个多边形都是wkt形式,如下所示:

list_polygons =  ['POLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200029))', 
                  'POLYGON ((-88.121359263 41.887694051,-88.12027565 41.887654116,-88.120264921 41.884451192,-88.11968556399999 41.884483142,-88.11962119099999 41.882669946,-88.121251974 41.882637995,-88.121359263 41.887694051))']

我想转换为多多边形wkt

'MULTIPOLYGON (((-88.131229288 41.900200029, -88.12973798 41.900104202, -88.12978599900001 41.894907769, -88.131352409 41.895051521, -88.131229288 41.900200029)), ((-88.121359263 41.887694051, -88.12027565 41.887654116, -88.120264921 41.884451192, -88.11968556399999 41.884483142, -88.11962119099999 41.882669946, -88.121251974 41.882637995, -88.121359263 41.887694051)))'

我尝试了以下操作,但给了我AssertionError

from shapely.geometry.multipolygon import MultiPolygon
Multipolygon(list_polygons)

我也试图像这样调试

p = wkt.loads('POLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200
029))')
*** SyntaxError: SyntaxError('invalid syntax', ('<string>', 1, 1, "= wkt.loads('POLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200029))')"))

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您的list_polygons实际上是一个字符串列表,您需要将它们转换为多边形,然后使用MultiPolygon构造函数创建所需的字符串:

import shapely.wkt as wkt
from shapely.geometry import MultiPolygon

list_string = [
    'POLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200029))',
    'POLYGON ((-88.121359263 41.887694051,-88.12027565 41.887654116,-88.120264921 41.884451192,-88.11968556399999 41.884483142,-88.11962119099999 41.882669946,-88.121251974 41.882637995,-88.121359263 41.887694051))'
]

c = MultiPolygon(map(wkt.loads, list_string))

print(c)

此示例使用地图,但是您可以随意使用wkt.loads()函数。

该行实际执行的操作:将wkt.loads()函数应用于list_string列表中的每个元素,并将生成的迭代器传递给MultiPolygon构造函数,该构造函数希望它表示应该表示的多边形集合形状的外部(不是孔,那是第二个集合)。