1. 程式人生 > 實用技巧 >10章程式碼

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('\n', '') #刪除\n
            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]+'\n') 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.3txt度分秒轉點

#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+"\n")

        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+"\n")

    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.5XLS的操作

10.5.1Excel表格轉點

# -*- 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))