[GIS] Splitting text from a string field before each delimiter to new fields

attribute-tablefield-calculatorpyqgisqgisqgis-custom-function

I'm trying to extract text data from a string field containing text delimited by dots and placing it in new fields using the field calculator.

Im using this python function (Taken from How to extract text before a / in QGIS?):

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def func(value1, feature, parent):
    return value1.split('.')[0]

This returns all text before the first dot. Now I'm wondering how to write the function for it to place each delimited text row in a separate field.

Before:

Tables

After:

Tables

Best Answer

EDIT: I edited the answer according to some comments by JWes.


You may run a simple script from the Python Console. Firstly, open the Python Console from Plugins > Python Console and activate the button for the Editor:

enter image description here

Then, load the object (a vector, a table, etc.) where your data are stored.

Once you have done this, copy the following code in the Editor:

layer = iface.activeLayer()
fieldindex = layer.fieldNameIndex("Tasks")
layer.startEditing()
for feat in layer.getFeatures():
    if feat[fieldindex]:
        fields = feat[fieldindex].split('.')
        for i in range(1, len(fields)):
            feat[fieldindex + i] = fields[i - 1]
            layer.updateFeature(feat)
    else:
        continue
layer.commitChanges()

and then run it:

enter image description here

You will obtain this:

enter image description here

If you prefer, you may obviously use the above code as a Python function for the field calculator (I saw that you already know how to do it).

Related Question