2019-07-12 15:40:12 3696瀏覽
本篇文章Python培訓(xùn)小編給大家分享一下如何解決Python ogr shp字段寫入中文亂碼的問(wèn)題,文中有代碼列出供小伙伴們參考,對(duì)Python開發(fā)感興趣的小伙伴就隨小編來(lái)了解一下吧。
首先,先確認(rèn)一下你的字段值是不是亂碼,如果是,按照以下方法:
我的字段值是來(lái)自于一個(gè)geojson字符串,我在對(duì)它解析時(shí)做了如下處理:
這樣即可消除字段值中的中文亂碼。
字段值沒(méi)有亂碼了,可是這樣寫入shp,shp中會(huì)出現(xiàn)亂碼,使用如下方法解決:
首先,你需要用driver方法創(chuàng)建shp文件而不是直接用ogr.open:
然后,在driver創(chuàng)建之前加入如下兩句:
成了。
源碼如下:
properties = fea.get("properties")
pro_json=json.dumps(properties)
pro_json.replace('u\'','\'')#將unicode編碼轉(zhuǎn)化為中文先處理一下
pro_json=pro_json.decode("unicode-escape") #將unicode編碼轉(zhuǎn)化為中文
properties=json.loads(pro_json)
driver=ogr.GetDriverByName("ESRI Shapefile")
ds =driver.CreateDataSource(shp_path)#打開要寫入的數(shù)據(jù)源
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)#打開要寫入的數(shù)據(jù)源
if ds is None:
sys.exit('Could not open this folder!')
if ds.GetLayer('test_polygon'):
ds.DeleteLayer('test_polygon')#如果存在,就刪除該數(shù)據(jù)
feature0=a['features'][0]
geo = feature0.get("geometry")
geo_type = geo.get('type')#獲取圖層類型
properties = feature0.get("properties")
keys=properties.keys()#獲取字段名稱數(shù)組
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)#創(chuàng)建圖層
#接下來(lái)往圖層中寫入feature
for key in keys:
field_testfield = ogr.FieldDefn(key, ogr.OFTString)#創(chuàng)建字段
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編碼轉(zhuǎn)化為中文先處理一下
pro_json=pro_json.decode("unicode-escape") #將unicode編碼轉(zhuǎn)化為中文
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)#創(chuàng)建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')
最后想要了解更多關(guān)于Python和人工智能方面內(nèi)容的小伙伴,請(qǐng)關(guān)注扣丁學(xué)堂Python培訓(xùn)官網(wǎng)、微信等平臺(tái),扣丁學(xué)堂IT職業(yè)在線學(xué)習(xí)教育平臺(tái)為您提供權(quán)威的Python開發(fā)環(huán)境搭建視頻,Python培訓(xùn)后的前景無(wú)限,行業(yè)薪資和未來(lái)的發(fā)展會(huì)越來(lái)越好的,扣丁學(xué)堂老師精心推出的Python視頻教程定能讓你快速掌握Python從入門到精通開發(fā)實(shí)戰(zhàn)技能??鄱W(xué)堂Python技術(shù)交流群:279521237。
【關(guān)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】 【掃碼進(jìn)入Python全棧開發(fā)免費(fèi)公開課】