Python OGR写入SHP中文乱码解决方案

云舒
云舒
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍在Python中使用OGR库写入SHP文件时解决中文乱码的方法。核心步骤包括:通过GDAL配置选项设置UTF-8文件名和GBK编码,以及处理GeoJSON属性中的Unicode编码转换。确保字段值正确解析并写入数据源,避免中文显示异常。

首先,请确认字段值是否确实存在乱码现象。若存在乱码,可参考后续步骤进行处理。

本例中,字段值源自GeoJSON字符串。在解析该字符串时,需执行特定的编码转换操作。

properties = fea.get("properties")
pro_json=json.dumps(properties)
pro_json.replace('u\'','\'')#将unicode编码转化为中文先处理一下
pro_json=pro_json.decode("unicode-escape") #将unicode编码转化为中文
properties=json.loads(pro_json)

经过上述处理,字段值中的中文乱码问题即可得到消除。

尽管字段值本身已无乱码,但直接写入SHP文件时仍可能出现乱码。此时需采用以下方法解决。

创建SHP文件时,必须使用driver方法,而非直接使用ogr.open。

driver=ogr.GetDriverByName("ESRI Shapefile")
ds =driver.CreateDataSource(shp_path)#打开要写入的数据源

在调用driver创建数据源之前,需添加以下两句配置代码。

gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
gdal.SetConfigOption("SHAPE_ENCODING", "GBK")

完成上述配置后,问题即可解决。

完整参考源码如下。

def create_shp_with_geoJson2(a,shp_path):
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
gdal.SetConfigOption("SHAPE_ENCODING", "GBK")
driver=ogr.GetDriverByName("ESRI Shapefile")
ds =driver.CreateDataSource(shp_path)#打开要写入的数据源
if ds is None:
sys.exit('Could not open this folder!')
if ds.GetLayer('test_polygon'):
ds.DeleteLayer('test_polygon')#如果存在,就删除该数据
feature0=a['features'][0]
geo = feature0.get("geometry")
geo_type = geo.get('type')#获取图层类型
properties = feature0.get("properties")
keys=properties.keys()#获取字段名称数组
if geo_type=='Polygon' or 'MultiPolygon':
ogr_type=ogr.wkbPolygon
else:
if geo_type=='Point':
ogr_type=ogr.wkbPoint
else:
if geo_type=='LineString' or 'MultiLineString':
ogr_type=ogr.wkbLineString
out_lyr=ds.CreateLayer('test_polygon',None,ogr_type)#创建图层
#接下来往图层中写入feature
for key in keys:
field_testfield = ogr.FieldDefn(key, ogr.OFTString)#创建字段
field_testfield.SetWidth(254)
out_lyr.CreateField(field_testfield)
for fea in a['features']:
geometry_json=fea.get("geometry")
properties = fea.get("properties")
pro_json=json.dumps(properties)
pro_json.replace('u\'','\'')#将unicode编码转化为中文先处理一下
pro_json=pro_json.decode("unicode-escape") #将unicode编码转化为中文
properties=json.loads(pro_json)
geom=ogr.CreateGeometryFromJson(str(geometry_json))
out_defn=out_lyr.GetLayerDefn()
out_feat=ogr.Feature(out_defn)
out_feat.SetGeometry(geom)#创建geometry
for i in range(len(keys)):
value=properties.get(keys[i])#获取属性值
print(value)
out_feat.SetField(i,value)
out_lyr.CreateFeature(out_feat)#在图层中插入该要素
if __name__ == '__main__':
create_shp_with_geoJson2(a,'web')

以上内容为Python OGR写入SHP字段中文乱码的解决方案,供读者参考。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表