ArcPy批量選擇指定屬性的要素


在GIS數據處理中,選擇數據是十分頻繁的操作,常用的是"按屬性選擇"和"按位置選擇",這兩個功能雖然比較強大,但有時也不能滿足實際需求。比如可能時常會遇到這樣一種情景:將指定OID(假設3和6)的要素選擇出來。

1、按屬性SQL選擇

最容易想到的是使用按屬性選擇構造WHERE子句("OBJECTID=3 OR OBJECTID=6")即可通過SQL選擇出來。

 

2、屬性連接

那么問題來了,如果給定的ID有100個,而且它們沒有什么規律,構造SQL語句會不會手軟呢?這也不難辦,使用屬性連接也可以選擇出來。

3、自定義選擇工具

有沒有簡便一點的、可重復使用的方式,不用連接、不用手動構造SQL子句,那就用代碼自動來構造查詢語句吧。

很簡單很實用的工具,代碼如下:

# -- 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、兼容字符串類型

上面的代碼寫得匆忙,只考慮了數字型,沒有考慮字符串型號的,有不同學在問,其實也很簡單啦,加一個引號就行。效果如下:

非字符串就不加引號:

代碼如下:

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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM