我遇到了这个问答,它帮助我解决了为什么无法在ArcPy搜索游标上使用where子句的问题,该子句可以将游标限制为仅包含_
在特定文本字段中包含下划线()的那些记录。
到我找到它的时候,我已经开发了一个代码片段来说明问题,因此,我没有在浪费精力,而是在上面添加了解决方案,现在将其发布在这里,以帮助将来有相同问题的访客。
该测试使用文件地理数据库,并且在ArcGIS 10.2.2 for Desktop上运行。
import arcpy
arcpy.CreateFileGDB_management(r"C:\Temp","test.gdb")
arcpy.CreateFeatureclass_management(r"C:\Temp\test.gdb","testFC")
arcpy.AddField_management(r"C:\Temp\test.gdb\testFC","testField","Text")
cursor = arcpy.da.InsertCursor(r"C:\Temp\test.gdb\testFC",["testField"])
cursor.insertRow(["ABCD"])
cursor.insertRow(["A_CD"])
cursor.insertRow(["XYZ"])
cursor.insertRow(["X_Z"])
del cursor
where_clause = "testField LIKE '%C%'"
print("Using where_clause of {0} to limit search cursor to print any values containing the letter C:".format(where_clause))
with arcpy.da.SearchCursor(r"C:\Temp\test.gdb\testFC",["testField"],where_clause) as cursor:
for row in cursor:
print(row[0])
print("This is the expected result :-)")
where_clause = "testField LIKE '%_%'"
print("\nUsing where_clause of {0} to limit search cursor to print any values containing an underscore (_):".format(where_clause))
with arcpy.da.SearchCursor(r"C:\Temp\test.gdb\testFC",["testField"],where_clause) as cursor:
for row in cursor:
print(row[0])
print("This is not what I was hoping for :-(")
where_clause = "testField LIKE '%$_%' ESCAPE '$'"
print("\nUsing where_clause of {0} to limit search cursor to print any values containing an underscore (_):".format(where_clause))
with arcpy.da.SearchCursor(r"C:\Temp\test.gdb\testFC",["testField"],where_clause) as cursor:
for row in cursor:
print(row[0])
print("This is what I was hoping for :-)")
输出为:
>>>
Using where_clause of testField LIKE '%C%' to limit search cursor to print any values containing the letter C:
ABCD
A_CD
This is the expected result :-)
Using where_clause of testField LIKE '%_%' to limit search cursor to print any values containing an underscore (_):
ABCD
A_CD
XYZ
X_Z
This is not what I was hoping for :-(
Using where_clause of testField LIKE '%$_%' ESCAPE '$' to limit search cursor to print any values containing an underscore (_):
A_CD
X_Z
This is what I was hoping for :-)
>>>
\
-我相信Oracle也是如此,因此如果要\_
搜索下划线,则需要查找。