[GIS] Problem with writing input and output for QGIS user script

geoprocessingpyqgisqgis-modelerqgis-processing

I need to write QGIS script, which removes features with same value of specific attribute – in output will be only features with first occurrence of value. I know, how to check duplicity, but I don't know, how properly create output from my script, when I need it to use in graphical modeler.

Also, what is the best way to get input into the script?

I am beginer in QGIS scripting, but I noticed that the basic scripts deal with inputs differently than any downloaded user scripts (which follow this documentation: https://docs.qgis.org/2.6/en/docs/user_manual/processing/scripts.html).

Best Answer

The following script can be used in the Processing Toolbox (either directly or through the modeler) which allows the user to select a field in the relevant layer and will only output the features with values which occur first:

##Delete first occurence=name
##input=vector
##field=field input
##output=output vector

from qgis.core import *

layer = processing.getObject(input)
provider = layer.dataProvider()
fields = provider.fields()
writer = QgsVectorFileWriter(output, 'UTF-8', fields, provider.geometryType(), layer.crs(), "ESRI Shapefile")

in_feat = QgsFeature()
out_feat = QgsFeature()
geom = QgsGeometry()
values = {}

value_field_index = layer.fieldNameIndex(field)

for in_feat in layer.getFeatures():
    geom = in_feat.geometry()
    attrs = in_feat.attributes()
    value = attrs[value_field_index]

    if value not in values:
        values[value]=[]
        out_feat.setGeometry(geom)
        out_feat.setAttributes(attrs)
        writer.addFeature(out_feat)

del writer

  • Attributes of input layer:

    Before script

  • Attributes of output layer:

    After script

Related Question