Skip to content

Instantly share code, notes, and snippets.

@mdouchin
Created February 22, 2017 10:21
Show Gist options
  • Save mdouchin/4b5ff8f37fbff11a491a2d4edcc693f1 to your computer and use it in GitHub Desktop.
Save mdouchin/4b5ff8f37fbff11a491a2d4edcc693f1 to your computer and use it in GitHub Desktop.
##Batch replace field value=name
##Vector_layer=vector
##Filter_expression=string "name" IS NOT NULL
##Source_field=string name
##Target_field=string short_name
##Replace_layer=table
##Replace_from=string name
##Replace_to=string short_name
##Replace_in_beginning=boolean False
##Replace_before=string
##output=output vector
from qgis.core import *
from processing.core.VectorWriter import VectorWriter
import re
# Get vector layer object
layer = processing.getObject(Vector_layer)
provider = layer.dataProvider()
table= processing.getObject(Replace_layer)
# Operate only on feature with a name
qExp = QgsExpression(Filter_expression)
qReq = QgsFeatureRequest(qExp)
features = layer.getFeatures( qReq )
# Create writer
writer = VectorWriter(output, None, provider.fields(),
provider.geometryType(), layer.crs())
# Export features
n = layer.featureCount()
for i, feat in enumerate(features):
progress.setPercentage(int(i *100 / n))
target = feat[Source_field]
# Get replacement data
# Do it inside the loop because an iterator is always destroyed once run
replaceList = table.getFeatures()
for t in replaceList:
# Replace search string by value
k = t[Replace_from]
v = t[Replace_to]
if Replace_in_beginning:
k = '^' + k
if Replace_before:
k = k + '(' + Replace_before + ')'
v = v + '\\1'
r = re.compile(k)
target = r.sub(v, target)
feat[Target_field] = target
writer.addFeature(feat)
del writer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment