zoukankan      html  css  js  c++  java
  • 10章代码

    10.1 文本读写

    #coding: UTF-8
    import arcpy
    import sys
    import codecs
    
    #文本返回数组
    def ReadTXTList(txtFile):
        sumlist=[]
        f = open(txtFile,"r") #
        try:
            lines = f.readlines()
            for line in lines:
                curline=line.replace('
    ', '') #删除
    
                sumlist.append(curline)
        finally:
            f.close()
        return sumlist
    #数组写到文件
    def WriteTXT(mylist,txtFile):
        wfiles = open(txtFile,'w')
        num=len(mylist)
    
        try:
            for i in range(num):
                wfiles.write(mylist[i]+'
    ')
        finally:
            wfiles.close()
        if wfiles:
            del wfiles
    
    arcpy.env.overwriteOutput = True
    inTxt = arcpy.GetParameterAsText(0)
    outTxt = arcpy.GetParameterAsText(1)
    #mylist=ReadTXT(inTxt)
    mylist=ReadTXTList(inTxt)
    WriteTXT(mylist,outTxt)

    10.2文本转点

    #coding: UTF-8
    #######################
    import arcpy
    import os
    import string
    import codecs
    
    
    def CreatePoint(line,cursor):
        arcpy.AddMessage("111111111111====================")
        if u""+line=="":#为空
            return
        arcpy.AddMessage(u""+line)
        xystr=string.split(u""+line,",")
        num=len(xystr)
        if num<2:
            return
        xstr=xystr[0] #
        ystr=xystr[1] #
    
        x=float(xstr) #dmstod(u""+xstr) #一定要加u
        y=float(ystr)  #dmstod(u""+ystr) #一定要加u
        arcpy.AddMessage("{0}======={1}".format(x,y))
        #cursor.insertRow(((x,y),))
        arcpy.AddMessage(u""+xstr+":"+ystr)
        cursor.insertRow((xstr,ystr,(x,y)))
    def ReadTXT(txtFile):
        f = codecs.open(txtFile,'r','gbk') #'utf-8'
    
        lines = f.readlines()
        f.close()
        return lines
    def main():
        lines=ReadTXT(txtFile)
    
        i=0
        num=len(lines)
        initProgress(u"创建数据",num)
        for line in lines:
            arcpy.AddMessage("i==="+str(i))
            if i==0:#加字段
                fields=addField(line)
                fields.append("SHAPE@XY")
                cursor = arcpy.da.InsertCursor(outFeature,fields)
                #cursor = arcpy.da.InsertCursor(outFeature,("Fx","FY","SHAPE@XY"))
                #cursor = arcpy.da.InsertCursor(outFeature,("SHAPE@XY"))
            else:
                CreatePoint(line,cursor)
            i+=1
            step()
        freeProgress()
    
    txtFile = arcpy.GetParameterAsText(0) #输入
    outFeature = arcpy.GetParameterAsText(1) #类型
    SR=arcpy.GetParameter(2) #坐标系
    sr = arcpy.SpatialReference()
    sr.loadFromString(SR)
    
    outPath, outFC = os.path.split(outFeature)
    if SR==None or str(SR)=="":
        arcpy.CreateFeatureclass_management(outPath, outFC, "POINT", "","","")
    else:#有坐标系
        arcpy.CreateFeatureclass_management(outPath, outFC, "POINT", "","","",sr)
    
    try:
        main()
        #arcpy.SetParameterAsText(3, inFeature)  # Is polygon
    except Exception, ErrorDesc:
        arcpy.AddError(u"错误:"+str(ErrorDesc))

    10.3  txt度分秒转点

    #coding: UTF-8
    #######################
    import arcpy
    import os
    import string
    import codecs
    
    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)
        FieldName=FieldName.upper()
        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 is_number(str):
        try:
            # 因为使用float有一个例外是'NaN'
            if str=='NaN':
                return False
            float(str)
            return True
        except ValueError:
            return False
    
    #必须是u类型==================u=======度分秒转度
    def dmstod(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("d="+str(d)+",m="+str(f)+",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: 转换后小数点后面第三四伴数
        '''
        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)
        return "%s°%s′%s″"%(bef0, aft012, aft034)
    
    
    def ReadTXT(txtFile):
        f = codecs.open(txtFile,'r','gbk') #'utf-8'
    
        lines = f.readlines()
        f.close()
        return lines
    def addField(line):
        fields=string.split(line,",")
        fd=[]
        for field in fields:
            myfield=field.upper().strip()
            fd.append(myfield)
            if not FieldExists(outFeature,myfield):
                arcpy.AddMessage("field========"+field)
                arcpy.AddField_management(outFeature,myfield , "TEXT", "", "", "255")
        return fd #重新获得字段,不用原来的,原来的后面有回车
    #有坐标生成点
    def createxyPoint(x,y,sr):
        point = arcpy.Point() #create an empty Point object
        point.X = x
        point.Y = y
        #return point
        pointGeometry = arcpy.PointGeometry(point,sr)
        return pointGeometry
    
    
    def CreatePoint(line,cursor):
        arcpy.AddMessage("111111111111====================")
        if u""+line=="":#为空
            return
        arcpy.AddMessage(u""+line)
        xystr=string.split(u""+line,",")
        num=len(xystr)
        if num<2:
            return
        xstr=xystr[0]
        ystr=xystr[1]
    
        x=dmstod(u""+xstr) #一定要加u
        y=dmstod(u""+ystr) #一定要加u
        arcpy.AddMessage("{0}======={1}".format(x,y))
        #cursor.insertRow(((x,y),))
        arcpy.AddMessage(u""+xstr+":"+ystr)
        cursor.insertRow((xstr,ystr,(x,y)))
    def main():
        lines=ReadTXT(txtFile)
    
        i=0
        num=len(lines)
        initProgress(u"创建数据",num)
        for line in lines:
            arcpy.AddMessage("i==="+str(i))
            if i==0:#加字段
                fields=addField(line)
                fields.append("SHAPE@XY")
                cursor = arcpy.da.InsertCursor(outFeature,fields)
                #cursor = arcpy.da.InsertCursor(outFeature,("Fx","FY","SHAPE@XY"))
                #cursor = arcpy.da.InsertCursor(outFeature,("SHAPE@XY"))
            else:
                CreatePoint(line,cursor)
            i+=1
            step()
        freeProgress()
    
    txtFile = arcpy.GetParameterAsText(0) #输入
    outFeature = arcpy.GetParameterAsText(1) #类型
    SR=arcpy.GetParameter(2) #坐标系
    sr = arcpy.SpatialReference()
    sr.loadFromString(SR)
    
    outPath, outFC = os.path.split(outFeature)
    if SR==None or str(SR)=="":
        arcpy.CreateFeatureclass_management(outPath, outFC, "POINT", "","","")
    else:
        arcpy.CreateFeatureclass_management(outPath, outFC, "POINT", "","","",sr)
    
    try:
        main()
        #arcpy.SetParameterAsText(3, inFeature)  # Is polygon
    except Exception, ErrorDesc:
        arcpy.AddError(u"错误:"+str(ErrorDesc))

    10.4 属性转TXT

    #coding=utf8
    import arcpy
    import os
    import sys
    
    import ylpy
    import string
    def add_error(id, s=None):
        """ Return errors """
    
        arcpy.AddIDMessage("ERROR", id, s if s else None)
        if __name__ == '__main__':
            sys.exit(1)
        else:
            raise arcpy.ExecuteError, arcpy.GetIDMessage(id)
    
    #获得一个字段类型
    def getFieldType(TableName,FieldName):
        desc = arcpy.Describe(TableName)
        FieldName=FieldName.upper()
        for field in desc.fields:
            if field.Name.upper() ==FieldName:
                return field.type
                break
        return ""
    def getFieldlen(TableName,FieldName):
        desc = arcpy.Describe(TableName)
        FieldName=FieldName.upper()
        for field in desc.fields:
            if field.Name.upper() ==FieldName:
                return field.length
                break
        return -1
    
    def main():
        #arcpy.AddMessage("==================")
        wfiles = open(txtFile,'w')
    
        try:
            myField=FieldNames.replace(";",",")
            wfiles.write(myField+"
    ")
    
            num=len(fields)
            #arcpy.AddMessage("num===="+str(num))
            FieldTypeList=[] #字段类型列表
            for  field in fields:
                FieldType=getFieldType(inFeature,field)
                FieldTypeList.append(FieldType)
    
            # Loop through input records
            n=ylpy.getCount(inFeature)
            ylpy.initProgress(u"导出数据",n)
            mystr='' #字符串
            with arcpy.da.SearchCursor(inFeature, fields) as cursor:
    
                for row in cursor:
                    ylpy.step()
                    myValue=""
                    for  i in range(0,num):
                        value=row[i]
                        if FieldTypeList[i]=="String":
                            if value==None:
                                value=mystr+mystr
                            else:
                                value=mystr+value+mystr
                            myValue=myValue+value
                        else:
                            if value==None:
                                myValue=myValue
                            else:
                                myValue=myValue+str(value)
                        if i<num-1:
                            myValue=myValue+","
                    wfiles.write(myValue+"
    ")
    
        finally:
            wfiles.close()
            ylpy.freeProgress()
        #arcpy.AddMessage("aaaaaaaaaaaaaa")
    inFeature = arcpy.GetParameterAsText(0) #
    FieldNames=arcpy.GetParameterAsText(1)
    txtFile=arcpy.GetParameterAsText(2) #是字符串的,一定要写成字符串
    
    fields=string.split(FieldNames,";")
    num=ylpy.getCount(inFeature)
    try:
        main()
        #arcpy.SetParameterAsText(3, inFeature)  # Is polygon
    except Exception, ErrorDesc:
        arcpy.AddError(u"错误:"+str(ErrorDesc))

    10.5 XLS的操作

    10.5.1 Excel表格转点

    # -*- coding: cp936 -*-
    import xlrd # must init xlrd
    import arcpy
    import os
    
    def get_sheet_names(in_excel):
    
        workbook = xlrd.open_workbook(in_excel)
        return [sheet.name for sheet in workbook.sheets()]
    def getField(sheet):
        out_fields = []
        # Generate the list of output fields
        for f in sheet.row_values(0):
            out_fields.append(f)
        return out_fields
    
    def main():
        if xField==yField:
            arcpy.AddMessage(u"X字段和Y字段不能一样")
            return
        outName = outFeature # out file
    
        fileName=xlsFile
        if os.path.exists(fileName):
            excel = xlrd.open_workbook(fileName) # get excel
            if sheet_name in [None, '', '#']:
                table = excel.sheets()[0]
            else:
                 table = excel.sheet_by_name(sheet_name)
            fields=getField(table)
            for field in fields:
                arcpy.AddMessage(u"字段名====={0}".format(field))
    
            xidx=fields.index(xField)
            yidx=fields.index(yField)
            #table = excel.sheets()[0] # get table by sheets index
            nrows = table.nrows # number of table's row
            ncols = table.ncols
            if xidx>ncols:
                arcpy.AddError(u"X字段{0}不能大于{1}".format(xidx,ncols))
                return
            if yidx>ncols:
                arcpy.AddError(u"Y字段{0}不能大于{1}".format(yidx,ncols))
                return
    
            arcpy.AddMessage(u"字段名{0}和{1}".format(xField,yField))
            arcpy.AddMessage(u"索引{0}和{1}".format(xidx,yidx))
            # get data
            pointGeometryList = [] # a list to hold the PointGeometry objects
            point = arcpy.Point() #create an empty Point object
            spRef = sr
    
    
            for i in range(1,nrows): # get row once
                x = table.cell(i,xidx).value
                y = table.cell(i,yidx).value
                point.X = float(x)
                point.Y = float(y)
                pointGeometry = arcpy.PointGeometry(point,sr)
                pointGeometryList.append(pointGeometry)
    
            arcpy.CopyFeatures_management(pointGeometryList,outName) # save the shape file
    xlsFile = arcpy.GetParameterAsText(0) #xls文件
    sheet_name=arcpy.GetParameterAsText(1)
    xField=arcpy.GetParameter(2)
    yField=arcpy.GetParameter(3)
    outFeature=arcpy.GetParameterAsText(4)
    
    SR=arcpy.GetParameter(5) #坐标系
    
    sr = arcpy.SpatialReference()
    sr.loadFromString(SR)
    
    try:
        main()
    
    except Exception, ErrorDesc:
        arcpy.AddError(u"错误:"+str(ErrorDesc))

    10.5.2   属性转excel

    #coding=utf8
    import arcpy
    import os
    import sys
    import xlwt
    import ylpy
    import string
    def add_error(id, s=None):
        """ Return errors """
    
        arcpy.AddIDMessage("ERROR", id, s if s else None)
        if __name__ == '__main__':
            sys.exit(1)
        else:
            raise arcpy.ExecuteError, arcpy.GetIDMessage(id)
    
    #获得一个字段类型
    def getFieldType(TableName,FieldName):
        desc = arcpy.Describe(TableName)
        FieldName=FieldName.upper()
        for field in desc.fields:
            if field.Name.upper() ==FieldName:
                return field.type
                break
        return ""
    def getFieldlen(TableName,FieldName):
        desc = arcpy.Describe(TableName)
        FieldName=FieldName.upper()
        for field in desc.fields:
            if field.Name.upper() ==FieldName:
                return field.length
                break
        return -1
    
    def main():
        #arcpy.AddMessage("==================")
        workbook = xlwt.Workbook(encoding = 'utf-8')
        #arcpy.AddMessage("11111111111111")
    
        worksheet = workbook.add_sheet("s1")
    
        styleDefault = xlwt.XFStyle()
        styleDate = xlwt.XFStyle()
        styleDate.num_format_str = 'YYYY-MM-DD'
    
        styleTime = xlwt.XFStyle()
        styleTime.num_format_str = 'h:mm'
    
        styleDateTime = xlwt.XFStyle()
        styleDateTime.num_format_str = 'YYYY-MM-DD h:mm'
    
        styleInt = xlwt.XFStyle()
        styleInt.num_format_str = '0'
        index=0
        #FieldTypeList=[] #字段类型列表
        for  field in fields:
            #arcpy.AddMessage("3=========="+str(index))
            worksheet.write(0, index, field , styleDefault)
            FieldType=getFieldType(inFeature,field)
            #FieldTypeList.append(FieldType)
            if FieldType=='String':
                length=getFieldlen(inFeature,field)
                worksheet.col(index).width = min(50, length) * 256
            else:
                worksheet.col(index).width = 16*256
            index+=1
        worksheet.set_panes_frozen(True)
        worksheet.set_horz_split_pos(1)
        worksheet.set_remove_splits(True)
    
        num=len(fields)
        #arcpy.AddMessage("num===="+str(num))
        style = styleDefault
        # Loop through input records
        n=ylpy.getCount(inFeature)
        ylpy.initProgress(u"导出数据",n)
        with arcpy.da.SearchCursor(inFeature, fields) as cursor:
            row_index = 1
            for row in cursor:
                ylpy.step()
                for  i in range(0,num):
                    value=row[i]
                    #arcpy.AddMessage("====111========="+str(i)+":"+value)
                    # write to the cell
                    if isinstance(value, datetime.datetime):
                        if (value.hour == 0) and (value.minute == 0):
                            style = styleDate
                        elif (value.year == 1899) and (value.month == 12) and (
                                value.day == 30):
                                    style = styleTime
                                    value = (value - datetime.datetime(1899, 12, 30, 0,
                                                                   0,
                                                                   0)).total_seconds() / 86400.0
                        else:
                            style = styleDateTime
                    elif isinstance(value, int):
                        style = styleInt
                    else:
                        style = styleDefault
    
                    worksheet.write(row_index, i, value, style)
                row_index+=1
        #finally:
        #arcpy.AddMessage("--------"+outxls)
        workbook.save(outxls)
        ylpy.freeProgress()
        #arcpy.AddMessage("aaaaaaaaaaaaaa")
    inFeature = arcpy.GetParameterAsText(0) #
    FieldNames=arcpy.GetParameterAsText(1)
    outxls=arcpy.GetParameterAsText(2) #是字符串的,一定要写成字符串
    
    fields=string.split(FieldNames,";")
    num=ylpy.getCount(inFeature)
    arcpy.AddMessage(str(num))
    if  num> 65535:
            # Input table exceeds the 256 columns limit of the .xls file format.
            add_error(1531)
    elif len(fields) > 255:
            # Input table exceeds the 65535 rows limit of the .xls file format.
            add_error(1530)
    
    try:
        main()
        #arcpy.SetParameterAsText(3, inFeature)  # Is polygon
    except Exception, ErrorDesc:
        arcpy.AddError(u"错误:"+str(ErrorDesc))

    10.5.3 Excel转面

    #coding=utf8
    import arcpy
    import os
    import sys
    
    import ylpy
    import string
    
    def main():
        yl999="yl999"
        arcpy.MakeXYEventLayer_management(inTable,XField,YField,yl999,spatial_reference="#",in_z_field="#")
        yl=arcpy.env.scratchFolder+"/yl.shp" #scratchWorkspace工作空间和临时路径
        arcpy.Select_analysis(yl999,yl,where_clause="#")
        yl999=arcpy.env.scratchWorkspace+"/yl999"
        arcpy.PointsToLine_management(yl,yl999,Line_Field=PField,Sort_Field="#",Close_Line="CLOSE")
        arcpy.FeatureToPolygon_management([yl999],
                                      outFeature)
        arcpy.Delete_management(yl)
        arcpy.Delete_management(yl999)
    
    
    
    inTable = arcpy.GetParameterAsText(0) #
    XField=arcpy.GetParameterAsText(1)
    YField=arcpy.GetParameterAsText(2)
    PField=arcpy.GetParameterAsText(3) #面字段
    outFeature=arcpy.GetParameterAsText(4)
    arcpy.env.OverWriteOutput = True
    
    
    try:
        main()
        #arcpy.SetParameterAsText(3, inFeature)  # Is polygon
    except Exception, ErrorDesc:
        arcpy.AddError(u"错误:"+str(ErrorDesc))

     

  • 相关阅读:
    Django+xadmin打造在线教育平台(八)
    Django+xadmin打造在线教育平台(七)
    Django+xadmin打造在线教育平台(六)
    Django+xadmin打造在线教育平台(五)
    Django+xadmin打造在线教育平台(四)
    Django+xadmin打造在线教育平台(三)
    Django+xadmin打造在线教育平台(二)
    Cognos组织架构介绍
    Echarts 的悬浮框tooltip显示自定义格式化
    Echarts中axislabel文字过长导致显示不全或重叠
  • 原文地址:https://www.cnblogs.com/gisoracle/p/13550912.html
Copyright © 2011-2022 走看看