#coding=utf8 import arcpy import os import math #获得各种比例尺的代号 def getScaleDM(idx): return chr(idx + 65) #有经纬度和图幅序号获得图幅号, #idx=0,为1:100万 #idx=1,为1:50万 #idx=2,为1:25万 #idx=3,为1:10万 #idx=4,为1:5万 #idx=5,为1:2.5万 #idx=6,为1:1万 #idx=7,为1:5千 #idx=8,为1:2千 #idx=9,为1:1千 #idx=10,为1:500 def getnewtf(ll, bb, idx): ScaleDM = getScaleDM(idx) a = int(math.floor(bb / 4) + 1); #b = int(ll / 6) + 31; b = int(ll //6) + 31; #cc = int(4.0 / dw); cc = int(4.0 // dw); #cc1 = int((bb - 4 * (a - 1)) / dw); #(int)((bb - 4 * (a - 1)) / dw) cc1 = int((bb - 4 * (a - 1)) // dw); #(int)((bb - 4 * (a - 1)) / dw) c = cc - cc1; if (c == 0): c = cc a = a + 1 #d = (int)((ll - 6 * (b - 31)) / dj) + 1 d = (int)((ll - 6 * (b - 31)) // dj) + 1 #arcpy.AddMessage("dddd="+str(d)) #arcpy.AddMessage("aaa="+str(a)) #arcpy.AddMessage("bbbb="+str(b)) resultstr = chr(a + 64) + str(b) #arcpy.AddMessage("resultstr="+resultstr) if (idx > 0): resultstr = resultstr + ScaleDM; mystr = str(c).zfill(3) resultstr = resultstr + mystr + str(d).zfill(3); return resultstr; #获得一个坐标的地理坐标系 def getGCSName(sr): if sr.type != "Geographic": if hasattr(sr, 'GCS'): return sr.GCS srname=sr.name sr1 = arcpy.SpatialReference() if srname.startswith("Xian_1980"): sr1.factoryCode=4610 #80 elif srname.startswith("Beijing_1954") or srname.find("Lambert")>0: sr1.factoryCode=4214 #54 elif srname.startswith("CGCS2000"): sr1.factoryCode=4490 #2000 else: sr1.factoryCode=4326 #1984 sr1.create() return sr1 else: return sr #把其他类型转字符串 def ConverttoStr(v): if type(v)==str: return v else: return str(v) #字段是否存在 def FieldExists(TableName,FieldName): desc = arcpy.Describe(TableName) for field in desc.fields: if field.Name.upper() ==FieldName: return True break return False #清除选择对象 def clearselect(in_data): arcpy.SelectLayerByAttribute_management(in_data, "CLEAR_SELECTION") arcpy.RefreshActiveView() #获得记录数 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 getlength(mystr): lenTxt = len(mystr) lenTxt_utf8 = len(mystr.decode('utf-8')) size = int((lenTxt_utf8 - lenTxt)/2 + lenTxt) #arcpy.AddMessage("'{0}'最后长度{1},lenTxt={2},lenTxt_utf8={3}".format(mystr,size,lenTxt,lenTxt_utf8)) #获得指定条件的记录数 def getwhereCount(inFeature,wherestr): my_temp="my_temp" #临时数据 arcpy.MakeFeatureLayer_management(inFeature,my_temp,wherestr) return getCount(my_temp) #获得一个表的FID def getOIDField(jfb_Select): desc = arcpy.Describe(jfb_Select) OIDField=desc.OIDFieldName return OIDField #删除一个要素中图形相同的,可以删除相同的点、线、面 def delsame(jfb_Select): desc = arcpy.Describe(jfb_Select) shapeName = desc.ShapeFieldName arcpy.DeleteIdentical_management(jfb_Select, [shapeName]) #获得点的距离 def pointDistance(pt1,pt2): return math.sqrt((pt1.X-pt2.X)*(pt1.X-pt2.X)+(pt1.Y-pt2.Y)*(pt1.Y-pt2.Y)) #添加一个数据到指定mxd 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 delAllField(inFeature): fieldList = arcpy.ListFields(inFeature) for field in fieldList: if not (field.type=="Geometry" or field.type=="OID" or not field.editable): arcpy.DeleteField_management(inFeature,field.name) #获得一个要素类合并后的图形,使用融合工具 def getLayerGeomtry(inFeature): num=getCount(inFeature) mytemp=inFeature if num>1:#融合在 mytemp="in_memory/mytemp999aa" arcpy.Dissolve_management(inFeature, mytemp,"", "", "MULTI_PART") desc = arcpy.Describe(mytemp) shapefieldname = desc.ShapeFieldName rows = arcpy.SearchCursor(mytemp) for row in rows: pgeometry=row.getValue(shapefieldname) if row: del row if rows: del rows return pgeometry #获得一个要素类合并后的图形,自己图形合并 def getLayerGeomtryPro(inFeature): desc = arcpy.Describe(inFeature) shapefieldname = desc.ShapeFieldName rows = arcpy.SearchCursor(inFeature) i=0 for row in rows: if i<1: pgeometry=row.getValue(shapefieldname) else: pgeometry=pgeometry.union(row.getValue(shapefieldname)) i=i+1 if row: del row if rows: del rows return pgeometry #更新一个表所有图形 def updateGeometry(inFeature,pgeometry2): desc = arcpy.Describe(inFeature) shapefieldname = desc.ShapeFieldName rows = arcpy.UpdateCursor(inFeature) for row in rows: row.setValue(shapefieldname,pgeometry2) rows.updateRow(row) if row: del row if rows: del rows #度转度分秒 def dtodmsint(num): ''' bef0: 小数点前面的值 aft012: 转换后小数点后面第一二位数 aft034: 转换后小数点后面第三四伴数 ''' 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) #判断一个字符串是否为数字 def is_number(str): try: # 因为使用float有一个例外是'NaN' if str=='NaN': return False float(str) return True except ValueError: return False #度分秒转度 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 #数字转字符保留几位小数 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 #度转度分秒(秒保留小数位secondNUM) def dtodmsbydouble(num,secondNUM): ''' 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 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 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 #从列表中获得元素的索引idx def listindex(mylist,aa): num=len(mylist) for i in range(num): if mylist[i]==aa: return i return -1 #两点线 def gettwoline(pt1,pt2): parray=arcpy.Array() parray.add(pt1) parray.add(pt2) polyline = arcpy.Polyline(parray,sr) parray.removeAll() return polyline #有坐标生成点 def createPoint(x,y): point = arcpy.Point() #create an empty Point object point.X = float(x) point.Y = float(y) return point #pointGeometry = arcpy.PointGeometry(point,sr) #return pointGeometry #有最小的xy和最大的XY生成面,有矩形范围生成面 def createPolygon(xx1,yy1,xx2,yy2): p1=createPoint(xx1,yy2) p2=createPoint(xx2,yy2) p3=createPoint(xx2,yy1) p4=createPoint(xx1,yy1) parray=arcpy.Array() parray.add(p1) parray.add(p2) parray.add(p3) parray.add(p4) parray.add(p1) polygon = arcpy.Polygon(parray,sr) parray.removeAll() return polygon #根据一个点创建矩形: def getRectbyPoint(pnt,width,hight): x=pnt.X y=pnt.Y xx1=x-width/2 xx2=x+width/2 yy1=y-hight/2 yy2=y+hight/2 pgeo= createPolygon(xx1,yy1,xx2,yy2) return pgeo #字符串转列表 def strtoList(text): text = text.decode('utf-8') pList=[] for i in text: pList.append(i) return pList #获得一个数据的工作空间 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 #根据TableName,增加所有字段到outFeature 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 #旋转某个点,rotateX,rotateY旋转X,y,rotateAngle是旋转角度 def rotateonePoint(pnt,rotateX,rotateY,rotateAngle): x=(pnt.X-rotateX)*math.cos(rotateAngle)-(pnt.Y-rotateY)*math.sin(rotateAngle)+rotateX # (x - rx0)*cos(a) - (y - ry0)*sin(a) + rx0 ; y=(pnt.X-rotateX)*math.sin(rotateAngle)-(pnt.Y-rotateY)*math.cos(rotateAngle)+rotateY #(x - rx0)*sin(a) + (y - ry0)*cos(a) + ry0 pt1 = arcpy.Point(x,y) return pt1 #旋转一个点对象 def MovePoint(pt): pnt= pt.getPart(0) return rotateonePoint(pnt) #旋转多点 def MoveMPoint(partgeometry): array = arcpy.Array() num=partgeometry.partCount for i in range(num): pt=partgeometry.getPart(i) pt=rotateonePoint(pt) array.add(pt) return array #旋转很多点 def MoveManyPoint(partgeometry): array = arcpy.Array() num=partgeometry.count for i in range(num): pt=partgeometry[i] pt=rotateonePoint(pt) array.add(pt) return array #把内多边形,分解出来 def splitNgeometry(mgeometry): num=mgeometry.count Sumarray = arcpy.Array() parray = arcpy.Array() for i in range(num): pt=mgeometry[i] if pt: parray.add(pt) else:#内多边形 Sumarray.add(parray) parray.removeAll() Sumarray.add(parray) return Sumarray #旋转一个对象 def Moveobj(geometry): part_count = geometry.partCount #有几部分 #arcpy.AddMessage("FID:"+str(FID)+",part_count:"+str(part_count)) Sumarray = arcpy.Array() for i in range(part_count): partgeometry=geometry.getPart(i) SpliArray=splitNgeometry(partgeometry) N=SpliArray.count #arcpy.AddMessage("NNNNN=====:"+str(N)) for j in range(N): Splitgeometry=SpliArray[j] array=MoveManyPoint(Splitgeometry) try: Sumarray.add(array) except Exception as err: arcpy.AddError("错误=============j:"+str(j)+","+err.message) return Sumarray #获得FID对应的图形 def getFID(FID,pFeatures): FIDField=getOIDField(pFeatures) wherestr="{0}={1}".format(FIDField,FID) #arcpy.AddMessage(u"===="+wherestr) with arcpy.da.SearchCursor(pFeatures, "SHAPE@",wherestr) as cursor: try: for row in cursor: #arcpy.AddMessage(u"————————"+wherestr) return row[0] finally: del cursor #获得对应FID的图形 def updateFID(FID,pFeatures,geo): FIDField=getOIDField(pFeatures) wherestr="{0}={1}".format(FIDField,FID) with arcpy.da.UpdateCursor(pFeatures, "SHAPE@",wherestr) as cursor: try: for row in cursor: row[0]=geo cursor.updateRow(row) finally: del cursor #删除对应FID def delFID(FID,pFeatures): FIDField=getOIDField(pFeatures) wherestr="{0}={1}".format(FIDField,FID) with arcpy.da.UpdateCursor(pFeatures, "SHAPE@",wherestr) as cursor: try: for row in cursor: cursor.deleteRow() finally: del cursor #更新某个字段的值 def updateFieldName(tablename,FieldName,Value): rows = arcpy.UpdateCursor(tablename) for row in rows: row.setValue(FieldName,Value) rows.updateRow(row) if row: del row del rows #获得一个图层所有的节点数 def getAllPointCount(fc): g = arcpy.Geometry() geometryList = arcpy.CopyFeatures_management(fc, g) n = 0 for geometry in geometryList: n += geometry.pointCount return n