You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将WKT格式坐标导出为Shapefile并解决float无len()报错

问题原因
  • 手动拆分字符串解析WKT的逻辑容错性极低,遇到格式微小差异就会解析出异常float值,是触发TypeError: object of type 'float' has no len()报错的核心原因
  • bindPolygonCoordinates无返回值通常为两个诱因:一是未正确导入shapely.geometry下的Polygon类,调用未定义类时会触发异常导致无返回;二是Python3中zip返回迭代器,部分版本shapely的Polygon构造函数不直接支持迭代器输入,需要转成列表
  • 旧版本geopandas的CRS定义方式{'init': 'epsg:4326'}已废弃,也可能触发连锁报错
最优实现方案

无需手动解析WKT,直接使用shapely官方提供的WKT解析工具,代码更简洁、容错性更高:

# 提前安装依赖:pip install geopandas shapely
import geopandas as gpd
from shapely import wkt

# 输入WKT格式坐标
fieldCoordinatesAsTextInWKTInEPSG4326 = "POLYGON((6.692790084436616 51.13237486727857,6.6918971115756305 51.132725423664596,6.6922145189906725 51.13301489625002,6.6926758177672 51.13291397940796,6.692650425173997 51.1327121450621,6.692430356032901 51.132520932762816,6.692790084436616 51.13237486727857))"

# 直接解析WKT为Polygon对象
polygon_geom = wkt.loads(fieldCoordinatesAsTextInWKTInEPSG4326)

# 构建GeoDataFrame
gdf = gpd.GeoDataFrame(
    index=[0],
    crs="EPSG:4326",
    geometry=[polygon_geom]
)

# 导出为Shapefile,替换为你需要的输出路径即可
gdf.to_file("output_polygon.shp", encoding='utf-8')
原有代码修正方案

如果需要保留手动解析WKT的逻辑,修正后的代码如下:

import geopandas as gpd
from shapely.geometry import Polygon

def extractLonLatFromPolygonInWKTFor(polygonInWKT):
    lons = []
    lats = []
    s = polygonInWKT.replace("POLYGON","")
    s = s.replace("((","")
    s = s.replace("))","")
    s = s.strip()
    lonsLats = s.split(",")
    for lonLatStr in lonsLats:
        lonLat = lonLatStr.strip().split()
        # 增加校验避免解析异常
        if len(lonLat) >= 2:
            lons.append(float(lonLat[0]))
            lats.append(float(lonLat[1]))
    return lons,lats

def bindPolygonCoordinates(longitudeValuesArray, latitudeValuesArray):
    # zip转list适配所有版本shapely
    return Polygon(list(zip(longitudeValuesArray, latitudeValuesArray)))

def buildGeoDataFrameForGeometry(geometry):
    return gpd.GeoDataFrame(index=[0], crs="EPSG:4326", geometry=[geometry])

# 调用逻辑
lons,lats = extractLonLatFromPolygonInWKTFor(fieldCoordinatesAsTextInWKTInEPSG4326)
boundingPolygonGeometry = bindPolygonCoordinates(lons, lats)
boundingGeometryAsGDF = buildGeoDataFrameForGeometry(boundingPolygonGeometry)

# 导出Shapefile
boundingGeometryAsGDF.to_file("output_polygon.shp", encoding='utf-8')

内容的提问来源于stack exchange,提问作者Amrmsmb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 05:06:03