借助python,实现文本wkt值转ArcGIS中shape图形
本文解决利用python实现wkt转shp;如若不会脚本,可利用软件生成shp,链接转至:https://blog.csdn.net/weixin_46489415/article/details/106680133
先上代码,后附详解:
代码详解
import osr
import ogr
from osgeo import ogr
#导入模块,首先保证模块在python环境中已安装,安装方式很多(如pip install ogr)。from osgeo import ogr这句话可写可不写,不写有可能会报错:ogr中找不到GetDriverByName(‘ESRI Shapefile’)。
outShapefile = r"E:\a\a.shp"
#定义输出路径及文件名称,a.shp文件不要存在于文件夹中
tabletxt = r"E:\a\cs.txt"
#定义输入文件路径,个人测试txt内容格式如下(个人可根据自己需要自行修改):
outDriver = ogr.GetDriverByName(‘ESRI Shapefile’)
outDataSource = outDriver.CreateDataSource(outShapefile)
#创建输出文件格式shapefile
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
outLayer = outDataSource.CreateLayer(“states_extent”, srs, geom_type=ogr.wkbPolygon)
#定义投影,4326值代表WGS84坐标系,ArcGIS中可以看到不同坐标系的WKID值进行调用。如果不想定义投影,此段代表可改成outLayer = outDataSource.CreateLayer(“states_extent”, geom_type=ogr.wkbPolygon)
aField = ogr.FieldDefn(“ID”, ogr.OFTString)
aField.SetWidth(254)
outLayer.CreateField(aField)
#创建字段,宽度值254我已设置成最大
featureDefn = outLayer.GetLayerDefn()
def addPoly(a,wktpoly):
feature = ogr.Feature(featureDefn)
feature.SetGeometry(wktpoly)
feature.SetField(“ID”, a)
outLayer.CreateFeature(feature)
feature = None
#创建shape图形
f = open(tabletxt,‘r’)
line = f.readline()
#文件可能比较大,逐行读取,可以自行去了解read、readline、readlines三者之间的区别
while line:
a,wktstr = line.split(";")
wktpoly = ogr.CreateGeometryFromWkt(wktstr)
addPoly(a, wktpoly)
line = f.readline()
f.close()
outDataSource = None
至此,即可将wkt值直接生成shape图形,如果原始数据字段较多,可采取两种方法:
一、只生成一个唯一关联字段,后面在ArcGIS中将表关联计算到shape数据中;
二、利用遍历方式,将表中字段依次遍历输出,一次性搞定。
完整代码:
import osr
import ogr
from osgeo import ogr
outShapefile = r"E:\a\a.shp"
tabletxt = r"E:\a\cs.txt"
outDriver = ogr.GetDriverByName(‘ESRI Shapefile’)
outDataSource = outDriver.CreateDataSource(outShapefile)
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
outLayer = outDataSource.CreateLayer(“states_extent”, srs, geom_type=ogr.wkbPolygon)
aField = ogr.FieldDefn(“ID”, ogr.OFTString)
aField.SetWidth(254)
outLayer.CreateField(aField)
featureDefn = outLayer.GetLayerDefn()
def addPoly(a,wktpoly):
feature = ogr.Feature(featureDefn)
feature.SetGeometry(wktpoly)
feature.SetField(“ID”, a)
outLayer.CreateFeature(feature)
feature = None
f = open(tabletxt,‘r’)
line = f.readline()
while line:
a,wktstr = line.split(";")
wktpoly = ogr.CreateGeometryFromWkt(wktstr)
addPoly(a, wktpoly)
line = f.readline()
f.close()
outDataSource = None