ArcPy批量选择指定属性的要素
在GIS数据处理中,选择数据是十分频繁的操作,常用的是"按属性选择"和"按位置选择",这两个功能虽然比较强大,但有时也不能满足实际需求。比如可能时常会遇到这样一种情景:将指定OID(假设3和6)的要素选择出来。
1、按属性SQL选择
最容易想到的是使用按属性选择构造WHERE子句("OBJECTID=3 OR OBJECTID=6")即可通过SQL选择出来。
2、属性连接
那么问题来了,如果给定的ID有100个,而且它们没有什么规律,构造SQL语句会不会手软呢?这也不难办,使用属性连接也可以选择出来。
3、自定义选择工具
有没有简便一点的、可重复使用的方式,不用连接、不用手动构造SQL子句,那就用代码自动来构造查询语句吧。
很简单很实用的工具,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | # -- coding:cp936 -- # --------------------------------------------------------------------------- # Fun : SelectFeatures # Author: gisweis # Date : 2020.10.25 # Email : # Notes : # --------------------------------------------------------------------------- import os import sys reload (sys) sys.setdefaultencoding( "utf-8" ) import arcpy import string try : #参数1:输入的图层或表 table = arcpy.GetParameterAsText( 0 ) #参数2:输入的字段名称 field = arcpy.GetParameterAsText( 1 ) #参数2:输入的编号文本 txt = arcpy.GetParameterAsText( 2 ) oid_fieldname = arcpy.Describe(table).OIDFieldName L = [] with open (txt, "r" ) as f: for line in f.readlines(): line = line.strip( '\n' ) if len (line) > 0 : L.append( ' ' + field + '=' + line + ' OR' ) L.append( ' ' + oid_fieldname + '<0' ) where = ''.join(L) arcpy.AddMessage(where) arcpy.SelectLayerByAttribute_management(table, "NEW_SELECTION" ,where) except arcpy.ExecuteError: arcpy.GetMessages() |
4、兼容字符串类型
上面的代码写得匆忙,只考虑了数字型,没有考虑字符串型号的,有不同学在问,其实也很简单啦,加一个引号就行。效果如下:
非字符串就不加引号:
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | # -- coding:cp936 -- # --------------------------------------------------------------------------- # Fun : SelectFeatures # Author: gisweis # Date : 2020.10.25 # Email : # Notes : 按属性列表选择指定要素 # --------------------------------------------------------------------------- import string import arcpy import os import sys reload (sys) sys.setdefaultencoding( "utf-8" ) try : #参数1:输入的图层或表 table = arcpy.GetParameterAsText( 0 ) #参数2:输入的字段名称 field = arcpy.GetParameterAsText( 1 ) #参数2:输入的编号文本 txt = arcpy.GetParameterAsText( 2 ) #获取 oid_fieldname = arcpy.Describe(table).OIDFieldName L = [] #判断是否字符串类型 sep = '' fieldType = arcpy.ListFields(table,field)[ 0 ] if (fieldType. type = = "String" ): sep = "'" with open (txt, "r" ) as f: for line in f.readlines(): line = line.strip( '\n' ) if len (line) > 0 : L.append( ' {0}={1}{2}{1} OR ' . format (field,sep,line)) L.append( ' {0}<0' . format (oid_fieldname)) where = ''.join(L) arcpy.AddMessage(where) arcpy.SelectLayerByAttribute_management(table, "NEW_SELECTION" , where) except arcpy.ExecuteError: arcpy.GetMessages() |
作者:我也是个傻瓜
出处:http://www.cnblogs.com/liweis/