4

I want to replace a string in ALL FIELDS / Columns of table without having to do it using field calculator in every field manually using replace( "RoadName1" ,'Wharf','WharfXXX').

I have

layer = iface.activeLayer()
searchText = "Wharf"
replaceText = "WharfXXX"
for field in layer.fields():
    fieldName=field.name()
    print (fieldName)
    for feature in layer.getFeatures():
        inText=str(feature[fieldName])
        #print (inText)
        if searchText in inText:
        #try QgsStringReplacement
            QgsStringReplacement(inText,replaceText, False, False)
        #try Field Calculator

            print ("Replaced %s with %s" %(inText,replaceText))
        else:
            #print ("not found")
            pass

It seems to work but I am not seeing any changes in the dataset.

I can't find any example implementations of https://qgis.org/api/classQgsStringReplacement.htmlenter image description here

Does this function do what I think it's supposed to -i.e. replace text when it matches?

I guess I could configure field calc to use these inputs but the function above seems cleaner in the long run.

processing.run("qgis:fieldcalculator", {'INPUT':'test.tab|layername=test','FIELD_NAME':'RoadName','FIELD_TYPE':0,'FIELD_LENGTH':10,'FIELD_PRECISION':3,'NEW_FIELD':False,'FORMULA':' replace( \"RoadName\" ,\'Warner\',\'WarnerXXX\')','OUTPUT':'memory:'})

2 Answers 2

5

You can try code below (backup data prior):

layer = iface.activeLayer()
textfields = [f.name() for f in layer.fields() if f.typeName()=='String']

replacedict = {'Hus,':'HusXYZ,','1':'ONE'}

with edit(layer):
    for feature in layer.getFeatures():
        for f in textfields:
            value = feature[f]
            if type(value)== str:
                new_value = ' '.join([replacedict[word] if word in replacedict else word for word in value.split()])
                _=feature.setAttribute(feature.fieldNameIndex(f), new_value)
                _=layer.updateFeature(feature)

From: enter image description here

To: enter image description here

If you want to replace parts of Words you can do:

layer = iface.activeLayer()
textfields = [f.name() for f in layer.fields() if f.typeName()=='String']

with edit(layer):
    for feature in layer.getFeatures():
        for f in textfields:
            value = feature[f]
            if type(value)== str:
                new_value = value.replace('Wharf','WharfXXX')
                _=feature.setAttribute(feature.fieldNameIndex(f), new_value)
                _=layer.updateFeature(feature)
4
  • very clean solution and I like that you can supply an array of all the changes to make HOWEVER - it's matching the whole word and not partial word. So 'Hus,' works but 'Hu' for example doesn't. Can it do a partial match?
    – GeorgeC
    Commented Apr 5, 2019 at 19:54
  • is it able to do a partial match?
    – GeorgeC
    Commented Apr 10, 2019 at 22:07
  • How can I do the same but for more than one value. For example, if a want to replace 'ab' by '12' and 'cd' by '34' and so on. Can I use the same code adding new lines?
    – Senda
    Commented Mar 4, 2020 at 10:48
  • @Senda I Think you should post that as a new question and include the code you tried with. (And a sample of the attribute table as text so people can copy paste and try with in QGIS). It is certainly possible without changing very much.
    – Bera
    Commented Mar 5, 2020 at 7:30
4

You can solve your problem using layer.changeAttributeValue() in an edit session.

layer = iface.activeLayer()
searchText = "Wharf"
replaceText = "WharfXXX"

# Start edit session for the layer
layer.startEditing()

for field in layer.fields():
    fieldName = field.name()
    # get field index
    fieldIndex = layer.fields().indexFromName(fieldName)

    for feature in layer.getFeatures():
        inText = str(feature[fieldName])

        if searchText in inText:
            # change inText
            outText = inText.replace(searchText, replaceText)
            # change field value of the attribute (in memory)
            layer.changeAttributeValue(feature.id(), fieldIndex, outText)

# save changes
layer.commitChanges()

Or you can use layer.dataProvider().changeAttributeValues(). In that case, you can change multiple fields at once. To see changes you may need to reopen the attribute table.

layer = iface.activeLayer()
searchText = "Wharf"
replaceText = "WharfXXX"

# get data provider
dpr = layer.dataProvider()

for field in layer.fields():
    fieldName=field.name()

    for feature in layer.getFeatures():
        inText = str(feature[fieldName])
        # get field index
        fieldIndex = layer.fields().indexFromName(fieldName)

        if searchText in inText:
            # change inText
            outText = inText.replace(searchText, replaceText)
            # save changes
            dpr.changeAttributeValues({feature.id(): {fieldIndex: outText}})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.