【问题标题】:Python GDAL, SetAttributeFilter not workingPython GDAL,SetAttributeFilter 不起作用
【发布时间】:2017-09-03 13:34:20
【问题描述】:

我正在尝试使用 GDAL 的 SetAttributeFilter() 过滤我的 shapefile 图层中的特征,但过滤器似乎没有效果。

我当前的数据是来自美国人口普查局的 shapefile,但我尝试使用其他 shapefile 并得到类似的结果。

例如

from osgeo import ogr

shapefile_path = '../input/processed/shapefile/'
shapefile_ds = ogr.Open(shapefile_path)
cbsa = shapefile_ds.GetLayer('cb_2016_us_cbsa_500k')

print(cbsa.GetFeatureCount())

cbsa.SetAttributeFilter('NAME = "Chicago-Naperville-Elgin, IL-IN-WI"')
feat = cbsa.GetNextFeature()

print(feat.GetField('NAME'))
print(cbsa.GetFeatureCount())

产量

945
Platteville, WI
945

我正在使用 Python 3.6 和 GDAL 2.2.1

【问题讨论】:

    标签: python-3.x gis gdal


    【解决方案1】:

    您可以捕获SetAttributeFilter 语句的返回值并确保其为0,否则会出错。

    在这种特殊情况下,可能是由于引用。单引号是指字符串文字(一个值),双引号是指列/表名。

    根据您运行此 Python 代码的方式,在 stdout/stderr GDAL 中的某处会打印如下内容: ERROR 1: "Chicago-Naperville-Elgin, IL-IN-WI" not recognised as an available field.

    更多详情请见: https://trac.osgeo.org/gdal/wiki/rfc52_strict_sql_quoting

    要让它工作,只需交换单/双引号,所以:

    cbsa.SetAttributeFilter("NAME='Chicago-Naperville-Elgin, IL-IN-WI'")

    【讨论】:

    • 你说得对,我得到的返回值为 5 并且交换了引号。非常感谢!
    【解决方案2】:

    虽然这是不久前的事,但当我学到一些东西时,我喜欢说一下在我的情况下什么是有效的,以防我再次搜索。

    对我来说,我必须使用如下语法:

    cbsa.SetAttributeFilter('"NAME" = \'Chicago-Naperville-Elgin\'')  # I didn't test multiple values
    

    接受答案的参考页面显示:

    <delimited identifier>     ::= <double quote> <delimited identifier body> <double quote>
    <character string literal> ::= <quote> [ <character representation> ... ] <quote>
    

    可能是自 17 年以来 ogr 的更新改变了这一点。

    【讨论】:

      猜你喜欢
      • 2018-02-25
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-11
      相关资源
      最近更新 更多