查看原文
其他

ArcGIS Python 按数据库标准创建要素类和表

GIS前沿 2023-04-16

数据库标准信息放在当前文件夹下Convert.mdb有“图层名”和“字段”两个表。“图层名”数据字段如下:表名是数据的别名,表英文是数据的名字,类型为0是表,1是点要素,2是线要素,3是面要素,4是注记,确定那个要素或表,如图14-7所示。“字段”表中数据,确定一个数据有那个字段和类型。“字段名”是表中字段别名,“字段英文”是真的字段名,ordid是字段顺序,如图14-8所示。


图14-7 数据库要素图层


图14-8 数据库中图层字段


图14-9 创建标准数据库运行界面


输入数据库,生成结果在数据库中的,输入文件夹,生成的数据为shp或dbf,没有的数据创建数据,已有数据,检查字段是否存在,没有字段增加字段,有字段,检查字段别名是否正确,不正确更新对应字段别名,如图14-9所示。


#coding=utf8
import arcpy

import os
import sys
import math
from arcpy.sa import *


#初始化进度条
def initProgress(hint,num):
    arcpy.SetProgressor(
"step", u"正在"+hint,0,num,1)
#进度条
def step():
    arcpy.SetProgressorLabel(
u"正在进行....")
    arcpy.SetProgressorPosition()
#释放进度条
def freeProgress():
    arcpy.ResetProgressor()
def getCount(inFeature):
    result = arcpy.GetCount_management(inFeature)
    count=
int(result.getOutput(0))
   
return count

#获得唯一值
def getuniqueValue(inTable,inField):
    rows = arcpy.da.SearchCursor(inTable,inField)
   
# Create an empty list
   
uniqueList = []
   
try:
       
for row in rows:
           
# If the value is not already in the list, append it
           
if row[0] not in uniqueList:
                uniqueList.append(row[
0])
       
return uniqueList
   
finally:
       
if row:
           
del row
       
if rows:
           
del rows

def getTable(tname):
    mypath=inWorkspace
    arcpy.env.workspace =mypath
   
if isshp==True:
       
if arcpy.Exists(mypath+os.sep+tname+".dbf"):
           
return mypath+os.sep+tname+".dbf"
   
else:
       
if arcpy.Exists(mypath+os.sep+tname):
           
return mypath+os.sep+tname

   
return None
def getFeatureclass(featurename):
    mypath=inWorkspace
    arcpy.env.workspace =mypath
   
if isshp==True:
       
if arcpy.Exists(mypath+os.sep+featurename+".shp"):
           
return mypath+os.sep+featurename+".shp"
   
else:
       
if arcpy.Exists(mypath+os.sep+featurename):
           
return mypath+os.sep+featurename
    datasets = arcpy.ListDatasets(
"", "Feature")
   
for dataset in datasets:
        curpath=mypath+os.sep+dataset
       
if arcpy.Exists(curpath+os.sep+featurename):
           
return curpath+os.sep+featurename
   
return None
def updateFieldalias(TableName,FieldName,alias):#更新字段别名
    desc = arcpy.Describe(TableName)
    FieldName=FieldName.upper()
   
for field in desc.fields:
       
if field.Name.upper() ==FieldName:
           
if field.aliasName!=alias:
                arcpy.AlterField_management(TableName, FieldName,
new_field_alias=alias) #修改别名
               
#field.aliasName=alias
               
arcpy.AddMessage(u"modify'table={2},{0}={1}'".format(FieldName,alias,TableName))
           
break

def
FieldExists(TableName,FieldName):#字段是否存在
    desc = arcpy.Describe(TableName)
   
for field in desc.fields:
       
if field.Name.upper() ==FieldName.upper():
           
return True
           
break
    return
False


def CreateTable(ftable):
    num=getCount(ftable)
    initProgress(
"create",num)
    inField=[
"表名","表英文","类型"]
    rows = arcpy.da.SearchCursor(ftable,inField)
   
try:
       
for row in rows:


            step()
            ptype=row[
2]
            etable=row[
1]
            ctable=row[
0]
            arcpy.AddMessage(
"etable="+etable+",ctable="+ctable)
           
if ptype==0:
                table= getTable(etable)
               
if table==None:
                    arcpy.CreateTable_management(inWorkspace, etable)
                   
if  not isshp:#数据库有别名
                       
arcpy.AlterAliasName(inWorkspace+os.sep+etable, ctable) #修改中文
           
elif ptype<4:
                inFeature=getFeatureclass(etable)

                geometry_type=
"POINT"
               
if ptype==2:
                    geometry_type=
"POLYLINE"
               
elif ptype==3:
                    geometry_type=
"POLYGON"

               
if inFeature==None:
                   
#sr = arcpy.Describe("JFB").spatialReference
                   
arcpy.CreateFeatureclass_management(inWorkspace, etable, geometry_type, spatial_reference=sr)
                   
#arcpy.CreateFeatureclass_management(inWorkspace, etable, geometry_type)
                    #template="#",has_m="DISABLED",has_z="DISABLED",spatial_reference=sr)

                   
if  not isshp:#数据库有别名
                       
arcpy.AlterAliasName(inWorkspace+os.sep+etable, ctable) #修改中文
   
finally:
        freeProgress()
       
if row:
           
del row
       
if rows:
           
del rows
def getFieldType(Fieldtype,Fieldlen):#返回标准的字段类型
    Fieldtype=Fieldtype.upper()
   
if Fieldtype=="INT" and Fieldlen<5:
       
return "SmallInteger"
   
elif Fieldtype=="INT":
       
return "Integer"
   
elif Fieldtype=="INTEGER":
       
return "Integer"
   
elif Fieldtype=="DOUBLE":
       
return "Double"
   
elif Fieldtype=="FLOAT":
       
return "Double"
   
elif Fieldtype=="STRING":
       
return "String"
   
elif Fieldtype=="CHAR":
       
return "String"
   
else:
       
return "Date"

def addoneField(fieldtable,sql,layername,inFeature):
    rows = arcpy.da.SearchCursor(fieldtable,[
"字段英文","字段名","字段类型","长度","小数位"],sql,sql_clause=(None,"order by ordid"))
   
try:
       
for row in rows:
            eField=row[
0]
            cField=row[
1]
            Fieldtype=row[
2]
            Fieldlen=row[
3]
            fieldPrecision=row[
4]
           
if not (FieldExists(inFeature,eField)):
                FType=getFieldType(Fieldtype,Fieldlen)
               
try:
                   
if FType.upper()=="Double".upper():
                        arcpy.AddField_management(inFeature, eField,
field_type="DOUBLE",field_precision=Fieldlen,field_scale=fieldPrecision,field_alias=cField)
                   
else:
                        arcpy.AddField_management(inFeature, eField, FType,
"#","#", Fieldlen,
                              cField)

               
except Exception, ErrorDesc:
                    arcpy.AddWarning(
u"错误:"+str(ErrorDesc))

   
finally:
       
if row:
           
del row
       
if rows:
           
del rows

def addField(layertable,fieldtable):
    num=getCount(layertable)
    inField=[
"表英文"]
    initProgress(
"addField",num)
    rows = arcpy.da.SearchCursor(layertable,inField)
   
try:
       
for row in rows:
            step()
            etable=row[
0]
            inFeature=getFeatureclass(etable)
           
if inFeature==None:
               
continue
           
sql="图层名='"+etable+"'"
           
addoneField(fieldtable,sql,etable,inFeature)

   
finally:
        freeProgress()
       
if row:
           
del row
       
if rows:
           
del rows

def Main():
    scriptPath = sys.path[
0]
    mdbpath=scriptPath+os.sep+
"Convert.mdb"
   
ftable=mdbpath+os.sep+"图层名"
   
fieldtable=mdbpath+os.sep+"字段"
   
CreateTable(ftable)
    addField(ftable,fieldtable)

inWorkspace=arcpy.GetParameterAsText(
0)
SR=arcpy.GetParameter(
1) #坐标系
#isclockwise=arcpy.GetParameter(4) #是否顺时针,软件自动处理,顺时针
sr = arcpy.SpatialReference()
sr.loadFromString(SR)

XY=arcpy.GetParameter(
2)

sr.XYTolerance=XY
arcpy.env.XYTolerance=
str(XY)+ " Meters"
outdesc = arcpy.Describe(inWorkspace)
isshp=
True

if outdesc.dataType== "Workspace":
    isshp=
False
   
Main()
elif not outdesc.dataType=="Folder":#FeatureDataset FeatureLayer
   
arcpy.AddError(u"格式错误无法裁剪")

else:
    Main()


文章授权转载:gisoracle

- END -

ArcGIS Pro花边图框的制作
国外15款最佳遥感软件
ArcGIS 各种坐标系文件下载
GIS=1/3地学+2/3信息科学?听武大教授谈GIS
实用工具 | ArcGIS顺序编号工具和快速查找文件下载

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存