• 6章代码


    6.1.2 获得唯一值的几种方法

    #coding=utf8
    import arcpy
    
    #获得重复的记录,使用set
    def getuniqueValues1():
        values = [row[0] for row in arcpy.da.SearchCursor(inFeature, (myField))]
        uniqueValues = set(values) #删除重复记录
        for v in uniqueValues:
            arcpy.AddMessage("v:"+v)
    #获得重复的记录,使用DISTINCT,排序的
    def getuniqueValues2():
        cursor=arcpy.da.SearchCursor(inFeature, (myField),sql_clause=("DISTINCT "+myField," order by "+myField))
        for row in cursor:
            arcpy.AddMessage("{0}".format(row[0]))
        del cursor
    #获得重复的记录 使用分组语句,排序的
    def getuniqueValues3():
        cursor=arcpy.da.SearchCursor(inFeature, (myField),sql_clause=(None,"group by "+myField+" order by "+myField))
        for row in cursor:
            arcpy.AddMessage("{0}".format(row[0]))
        del cursor
    
    inFeature=arcpy.GetParameterAsText(0)
    myField=arcpy.GetParameterAsText(1)
    getuniqueValues1()
    getuniqueValues2()
    getuniqueValues3()

    6.2 更新游标

    import arcpy
    from arcpy import env
    import os
    
    import sys
    import time
    import ylpy
    
    fc= arcpy.GetParameterAsText(0)
    fieldname= arcpy.GetParameterAsText(1)
    num=ylpy.getCount(fc)
    fields = [fieldname,'SHAPE@AREA']
    start = time.clock()
    workspace=ylpy.getWorkspace(fc)
    edit = arcpy.da.Editor(workspace)
    try:
        edit.startEditing(False, True) #写在前面,gisoracle
        edit.startOperation()
        i=1
        with arcpy.da.UpdateCursor(fc, fields) as cursor:
            for row in cursor:
                row[0] = row[1]
                cursor.updateRow(row)
                i=i+1
    
        # Stop the edit operation.
        edit.stopOperation()
    
        # Stop the edit session and save the changes
        edit.stopEditing(True)
    except arcpy.ExecuteError:
        arcpy.AddMessage("==="+arcpy.GetMessages(2))
    
    
    elapsed = (time.clock() - start)
    arcpy.AddMessage("Time used:"+str(elapsed)+","+str(i))

    6.2.1 椭球面积计算

    方法一:使用计算字段CalculateField,
    import arcpy
    from arcpy import env
    import os
    
    import sys
    import time
    fc= arcpy.GetParameterAsText(0)
    fieldname= arcpy.GetParameterAsText(1)
    
    arcpy.CalculateField_management(in_table=fc, field=fieldname, expression="!shape.geodesicArea!", expression_type="PYTHON_9.3", code_block="")
    方法二:使用“添加几何属性(AddGeometryAttributes)”
    # -*- coding: utf-8 -*-
    import arcpy
    arcpy.env.overwriteOutput = True
    infc= arcpy.GetParameterAsText(0)
    arcpy.AddGeometryAttributes_management(Input_Features=infc,Geometry_Properties="AREA_GEODESIC", Length_Unit="", Area_Unit="", Coordinate_System="")

    6.2.2 更新日期

    #coding=utf8
    import arcpy
    
    import os
    import sys
    import math
    import datetime
    
    def updatedate():
        fields = [inField]
        with arcpy.da.UpdateCursor(inTable, fields) as cursor:
            i=1
            for row in cursor:
                #mystr=row[0]+u" 长度"+str(i)
                #row[0]=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                row[0]=(datetime.datetime.now()+datetime.timedelta(days=i)).strftime("%Y-%m-%d %H:%M:%S")
                #row[0]="2019-11-08 19:07:43" #字符和
                cursor.updateRow(row)
                i=i+1
    
    def main():
    
        updatedate()
    
    inTable=arcpy.GetParameterAsText(0)
    inField=arcpy.GetParameterAsText(1)
    main()

    6.2.3  BLOB字段处理

    #coding=utf8
    import arcpy
    
    import os
    import sys
    import math
    import datetime
    
    def InsertBLOB():
        data = open("d:/1.png", "rb").read()
        ic = arcpy.da.InsertCursor(inTable, [inField])
        ic.insertRow([data])
        del ic
    def SearchBLOB():
        sc = arcpy.da.SearchCursor(inTable, [inField])
        memview = sc.next()[0]
        if memview!=None:
            open("d:/2.png", "wb").write(memview.tobytes())
        del sc
    def updateBLOB():
        data = open("d:/1.png", "rb").read()
        cursor = arcpy.da.UpdateCursor(inTable, [inField])
        for row in cursor:
            row[0]=data
            cursor.updateRow(row)
        del cursor
    
    def main():
        updateBLOB()
        SearchBLOB()
    
    inTable=arcpy.GetParameterAsText(0)
    inField="bb"
    main()

    6.2.4 删除记录

    #coding=utf8
    import arcpy
    
    import os
    import sys
    import math
    import datetime
    
    def deldata():
        fields = ["OID@"]
        with arcpy.da.UpdateCursor(outTable, fields) as cursor:
    
            for row in cursor:
                cursor.deleteRow()
    
    def main():
    
        deldata()
    
    inTable=arcpy.GetParameterAsText(0)
    outTable=arcpy.GetParameterAsText(1)
    desc = arcpy.Describe(inTable)
    isTable=desc.dataType=="TableView"
    if isTable==True:
        arcpy.TableSelect_analysis(inTable, outTable)
    else:
        arcpy.Select_analysis(inTable, outTable)
    main()

    6.2.6 添加经纬度坐标

    #coding: UTF-8
    #######################
    import arcpy
    import os
    import types
    import string
    
    def getCount(inFeature):
        result = arcpy.GetCount_management(inFeature)
        count= int(result.getOutput(0))
        return count
    def getwhereCount(inFeature,wherestr):
        my_temp="my_temp" #临时数据
    
        arcpy.MakeFeatureLayer_management(inFeature,my_temp,wherestr)
        return getCount(my_temp)
    def FieldExists(TableName,FieldName):
        desc = arcpy.Describe(TableName)
        for field in desc.fields:
            if field.Name.upper() ==FieldName:
                return True
                break
        return False
    
    def getOIDField(jfb_Select):
        desc = arcpy.Describe(jfb_Select)
        OIDField=desc.OIDFieldName
        return OIDField
    
    def initProgress(hint,num):
        arcpy.SetProgressor("step", u"正在"+hint,0,num,1)
    def step():
        arcpy.SetProgressorLabel(u"正在进行....")
        arcpy.SetProgressorPosition()
    def freeProgress():
        arcpy.ResetProgressor()
    def is_number(str):
        try:
            # 因为使用float有一个例外是'NaN'
            if str=='NaN':
                return False
            float(str)
            return True
        except ValueError:
            return False
    
    #必须是u类型==================u====================
    def dmstod(dms):
        #arcpy.AddMessage("================================="+dms+"==============================")
        try:
            p = dms.find('°')
            if p<0:
                return str(dms)
            #arcpy.AddMessage("p="+str(p))
            d=string.atof(dms[0:p].strip())
            #arcpy.AddMessage("d="+str(d))
            p1=dms.find('')
            #arcpy.AddMessage("p1="+str(p1))
            if p1<0:
                 p1=dms.find("'")
    
            f=0 #
            if p1>0:
                f=string.atof(dms[p+1:p1].strip())
            else:
                p1=p
            #arcpy.AddMessage("f="+str(f))
    
            p2=dms.find('')
            if p2<0:
                 p2=dms.find('"')
            #arcpy.AddMessage("p2="+str(p2))
    
            s=0 #
            if p2>0:
                s=string.atof(dms[p1+1:p2].strip())
            #arcpy.AddMessage("s="+str(s))
    
            return d+f/60+s/3600
        except ValueError:
            return None
    #获得一个点的投影坐标系
    def getpjxy(gx,gy,sr,GCSsr):
        point = arcpy.Point()
        point.X = gx
        point.Y = gy
    
        pointGeometry = arcpy.PointGeometry(point,GCSsr)
        newpointgeo=  pointGeometry.projectAs(sr)
        p1=newpointgeo.firstPoint
        return p1.X,p1.Y
    #获得一个点的经纬度坐标系
    def getGCSxy(gx,gy,sr,GCSsr):
        point = arcpy.Point()
        point.X = gx
        point.Y = gy
    
        pointGeometry = arcpy.PointGeometry(point,sr)
        newpointgeo=  pointGeometry.projectAs(GCSsr)
        p1=newpointgeo.firstPoint
        return p1.X,p1.Y
    def dtodmsint(num):
        '''
        bef0: 小数点前面的值
        aft012: 转换后小数点后面第一二位数
        aft034: 转换后小数点后面第三四伴数
        '''
        if not isinstance(num,float):
            num = eval(num)
    
        bef0, aft0 = int(num), num-int(num)
    
        aft012, aft034_t = int(aft0*60), aft0*60-int(aft0*60)
    
        aft034 = int(round(aft034_t*60))
    
        if aft034 < 10:
            aft034 = '0'+str(aft034)
    
        elif aft034 == 60:
            aft034='00'
            aft012 += 1
            if aft012==60:
                bef0=bef0+1
                aft012=0
    
        elif aft034 > 60:
            print "error:%s"%aft034
    
        if aft012<10:aft012 = '0' + str(aft012)
    
    
        return "%s°%s′%s″"%(bef0, aft012, aft034)
    #数字转字符保留几位小数  by gisoracle
    def floattostr(num,xsnum):
        if xsnum==0:
            return str(int(num))
        nd=round(num,xsnum)
        nstr=str(nd)
        idx=nstr.index('.')
        print idx
        p=len(nstr)-idx-1
        print p
        n=xsnum-p
        print n
        s=""
        for i in range(n):
            s=s+"0"
    
        return nstr+s
    
    
    def dtodmsbydouble(num):
        '''
        bef0: 小数点前面的值
        aft012: 转换后小数点后面第一二位数
        aft034: 转换后小数点后面第三四伴数
        '''
        fz=False #是否负数
        if num<0:
            fz=True
            num=abs(num)
    
        if secondNUM<1:
            return dtodmsint(num)
        if not isinstance(num,float):
            num = eval(num)
    
        bef0, aft0 = int(num), num-int(num)
    
        aft012=int(aft0*60)
        aft034_t = aft0*60-int(aft0*60)
    
        aft034 =aft034_t*60
        #arcpy.AddMessage("aft034:"+str(aft034))
        aft034=round(aft034,secondNUM)
    
        if aft034 < 10:
            aft034 = '0'+str(aft034)
    
        elif aft034 == 60:
            aft034='00'
            aft012 += 1
            if aft012==60:
                bef0=bef0+1
                aft012=0
    
        elif aft034 > 60:
            print "error:%s"%aft034
    
        aft034=floattostr(float(aft034),secondNUM)
    
        if aft012<10:aft012 = '0' + str(aft012)
        if fz:
            return "-%s°%s′%s″"%(bef0, aft012, aft034)
        else:
            return "%s°%s′%s″"%(bef0, aft012, aft034)
    
    #获得字段类型是否为文本
    def getFieldTypeIsText(TableName,FieldName):
        desc = arcpy.Describe(TableName)
        FieldName=FieldName.upper()
        for field in desc.fields:
            if field.Name.upper() ==FieldName:
                return field.type=="String"
    
        return False
    
    def main():
        num=getCount(inFeature)
        if num<1:
            arcpy.AddMessage(u"输入{0}没有记录".format(inFeature))
            return
        if sr.name == "Unknown":
            arcpy.AddError("请{0}定义坐标系,没有定义坐标!".format(inFeature))
            return
        lfname="经度"
        bfname="纬度"
        if FieldExists(inFeature,lfname):
            if not getFieldTypeIsText(inFeature,lfname):
                arcpy.DeleteField_management(inFeature,lfname)
    
        if not FieldExists(inFeature,lfname):
            arcpy.AddField_management(inFeature,lfname , "TEXT", "", "", "32")
    
        if FieldExists(inFeature,bfname):
            if not getFieldTypeIsText(inFeature,bfname):
                arcpy.DeleteField_management(inFeature,bfname)
        if not FieldExists(inFeature,bfname):
            arcpy.AddField_management(inFeature,bfname , "TEXT", "", "", "32")
        #shapeType=desc.shapeType
    
        initProgress("update",num)
        with arcpy.da.UpdateCursor(inFeature, [lfname,bfname,"SHAPE@XY"]) as cursor:
            for row in cursor:
                x, y = row[2]
                if GCSsr.factoryCode!=sr.factoryCode: #不是地理坐标系
                    x,y=getGCSxy(x,y,sr,GCSsr)
    
                if isdms==True:#是度分秒
                    xdms=dtodmsbydouble(x)
                    ydms=dtodmsbydouble(y)
                else:
                    xdms=floattostr(x,secondNUM)
                    ydms=floattostr(y,secondNUM)
                row[0]=xdms
                row[1]=ydms
    
                step()
                cursor.updateRow(row)
        freeProgress()
    
    inFeature = arcpy.GetParameterAsText(0) #输入
    lx = arcpy.GetParameterAsText(1) #类型
    isdms=lx=="度分秒"
    secondNUM= arcpy.GetParameter(2) #小数位数
    desc=arcpy.Describe(inFeature)
    sr =desc.spatialReference
    GCSsr=sr.GCS
    
    try:
        main()
        #arcpy.SetParameterAsText(3, inFeature)  # Is polygon
    except Exception, ErrorDesc:
        arcpy.AddError(u"错误:"+str(ErrorDesc))

    6.3.1 要素转点

    import arcpy
    import os
    #获得记录数
    def getCount(inFeature):
        result = arcpy.GetCount_management(inFeature)
        count= int(result.getOutput(0))
        return count
    #初始化进度条
    def initProgress(hint,num):
        arcpy.SetProgressor("step", u"正在"+hint,0,num,1)
    #进度条
    def step():
        arcpy.SetProgressorLabel(u"正在进行....")
        arcpy.SetProgressorPosition()
    #释放进度条
    def freeProgress():
        arcpy.ResetProgressor()
    
    def AddAllField(TableName,outFeature):
        desc = arcpy.Describe(TableName)
        plist = []
        for field in desc.fields:
            if field.type!="Geometry" and field.type!="OID" and field.editable:
    ##            arcpy.AddField_management(outFeature,field.Name ,field.type,
    ##            field.precision,field.scale,field.length)
                plist.append(field.Name)
        return plist
    
    def main():
        FieldList= AddAllField(inFeature,outFeature)
        FieldList.append("SHAPE@")
        num=len(FieldList)
        insertcursor = arcpy.da.InsertCursor(outFeature,FieldList)
        n=getCount(inFeature)
        initProgress("topoint",n)
    
        with arcpy.da.SearchCursor(inFeature, FieldList) as cursor:
            for row in cursor:
                step()
                myvalue = []
                for i in range(0,num-1):
                    #arcpy.AddMessage("i=="+str(i))
                    myvalue.append(row[i])
    
                geometry=row[num-1]
                if isinside:
                    Point=geometry.labelPoint
                else:
                    Point=geometry.centroid
                #arcpy.AddMessage("append===")
                myvalue.append(Point)
                insertcursor.insertRow(myvalue)
        freeProgress()
    
    inFeature=arcpy.GetParameterAsText(0)
    outFeature=arcpy.GetParameterAsText(1)
    isinside=arcpy.GetParameter(2) ##是否内部点
    sr = arcpy.Describe(inFeature).spatialReference
    outPath, outFC = os.path.split(outFeature)
    #arcpy.CreateFeatureclass_management(outPath, outFC, "POINT", "","","",sr)
    arcpy.CreateFeatureclass_management(outPath, outFC, "POINT", inFeature,"","",sr)
    try:
        main()
        #arcpy.SetParameterAsText(3, inFeature)  # Is polygon
    except Exception, ErrorDesc:
        arcpy.AddError(u"错误:"+str(ErrorDesc))

    6.3.2 距离角度生成点

    #coding=utf8
    import arcpy
    
    import os
    import sys
    import math
    def AddLayer(mxd,inFeature):
    
        df=arcpy.mapping.ListDataFrames(mxd)[0]
        addLayer = arcpy.mapping.Layer(inFeature)
        arcpy.mapping.AddLayer(df, addLayer,"AUTO_ARRANGE") #AUTO_ARRANGE,"BOTTOM",TOP
    
    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 getWorkspace(inFeature):
        desc = arcpy.Describe(inFeature)
        path=desc.path.lower()
        if path.endswith(".mdb") or path.endswith(".gdb"):
            return path
        if os.path.isdir(path):#shp
            return path
        outPath, outFC = os.path.split(path)
        return outPath
    
    def getonePoint(pnt,dis,angle):
        x=pnt.X+dis*math.cos(angle)
        y=pnt.Y+dis*math.sin(angle)
        pt1 =  arcpy.Point(x,y)
        return pt1
    def getnewPoint(pt,dis,angle):
        return getonePoint(pt,dis,angle)
    def AddAllField(TableName,outFeature):
        desc = arcpy.Describe(TableName)
        plist = []
        for field in desc.fields:
            if field.type!="Geometry" and field.type!="OID":
                plist.append(field.Name)
                arcpy.AddField_management(outFeature,field.Name ,field.type,field.precision,field.scale,field.length)
        return plist
    def gettwoline(pt1,pt2):
        parray=arcpy.Array()
        parray.add(pt1)
        parray.add(pt2)
        polyline = arcpy.Polyline(parray)
        parray.removeAll()
        return polyline
    def getLayer(layername):
        layername=layername.upper()
        mxd = arcpy.mapping.MapDocument("CURRENT")
        try:
            for lyr in arcpy.mapping.ListLayers(mxd):
                if lyr.name.upper()==layername:
                    return lyr
            return None
        finally:
            del mxd
    
    def Main():
        count=getCount(inFeature)
        if count < 1:
            arcpy.AddMessage(inFeature+u"没有数据")
            return
    
        arcpy.Select_analysis(inFeature, outFeature, '')
    
        desc = arcpy.Describe(inFeature)
        layername=desc.name
        shapeType=desc.shapeType
    
        shapeName = desc.ShapeFieldName
        OIDField=desc.OIDFieldName
        initProgress(u"正在",count)
        workspace=getWorkspace(inFeature)
    
        if outFeatureLine!="":
            cursor = arcpy.InsertCursor(outFeatureLine)
            desc1 = arcpy.Describe(outFeatureLine)
            shapeName = desc1.ShapeFieldName
    
        rows = arcpy.UpdateCursor(outFeature)
        desc = arcpy.Describe(outFeature)
        geoName = desc.ShapeFieldName
    
        try:
            for row in rows:
                step()
                #FID=row[0]
                pt = row.getValue(geoName)
                pnt1= pt.getPart(0)
                dis=row.getValue(disFieldName)
                a=row.getValue(angleField)
                if lx!="数学角度":
                    a=90-a
                angle=a*3.1415926/180
                pnt2=getnewPoint(pnt1,dis,angle)
    
                row.setValue(geoName,pnt2)
                rows.updateRow(row)
                if outFeatureLine!="":
                    pline=gettwoline(pnt1,pnt2)
                    myrow = cursor.newRow()
                    myrow.setValue(disFieldName,dis)
                    myrow.setValue(angleField,angle)
                    myrow.setValue(shapeName,pline)
                    cursor.insertRow(myrow)
    
        finally:
            freeProgress()
            #del row
            del rows
    
    inFeature  = arcpy.GetParameterAsText(0)
    disFieldName = arcpy.GetParameterAsText(1)
    angleField  = arcpy.GetParameterAsText(2)
    outFeature  = arcpy.GetParameterAsText(3) #输出点
    outFeatureLine= arcpy.GetParameterAsText(4)
    lx=arcpy.GetParameterAsText(5)
    if outFeatureLine!="":
        sr = arcpy.Describe(inFeature).spatialReference
        outPath, outFC = os.path.split(outFeatureLine)
        arcpy.CreateFeatureclass_management(outPath, outFC, "POLYLINE", "","","",sr)
        AddAllField(inFeature,outFeatureLine)
    Main()
    if outFeatureLine!="":
        layername=outFC
        myLayer=getLayer(layername)
        if myLayer==None:
            mxd = arcpy.mapping.MapDocument("CURRENT")
            AddLayer(mxd,outFeatureLine)
  • 相关阅读:
    Test_StringBuilder
    什么是朋友
    Uncharted4-Resource-Extract
    在使用 .NET Remoting 技术开发跨进程通信时Remoting找不到请求的服务--解决方法
    SourceTree 拉取github资源包时报错:fatal: unable to access 'https://github.com/xxx.git/': OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443 --解决办法
    .net core3.1 文件导出报错The type initializer for 'Gdip' threw an exception 的解决方法
    .net core3.1文件下载之MimeTypeMapHelper
    .net core3.1 webapi项目部署在centos7中,通过supervisor来做进程守护遇到backoff Exited too quickly (process log may have details)的错误--并提供解决方法
    jenkins安装在ubuntu的解决方法-运维系列
    supervisord.conf配置文件详情
  • 原文地址:https://www.cnblogs.com/gisoracle/p/13685840.html
Copyright © 2020-2023  润新知