您好,登錄后才能下訂單哦!
首先,先確認(rèn)一下你的字段值是不是亂碼,如果是,按照以下方法:
我的字段值是來自于一個(gè)geojson字符串,我在對(duì)它解析時(shí)做了如下處理:
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)
這樣即可消除字段值中的中文亂碼。
字段值沒有亂碼了,可是這樣寫入shp,shp中會(huì)出現(xiàn)亂碼,使用如下方法解決:
首先,你需要用driver方法創(chuàng)建shp文件而不是直接用ogr.open:
driver=ogr.GetDriverByName("ESRI Shapefile") ds =driver.CreateDataSource(shp_path)#打開要寫入的數(shù)據(jù)源
然后,在driver創(chuàng)建之前加入如下兩句:
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)建圖層 #接下來往圖層中寫入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')
以上這篇解決python ogr shp字段寫入中文亂碼的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。