Search and Replace text in All Fields in QGIS 3
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}
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.html
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:'})
pyqgis pyqgis-3 qgsstringreplacement
add a comment |
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.html
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:'})
pyqgis pyqgis-3 qgsstringreplacement
add a comment |
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.html
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:'})
pyqgis pyqgis-3 qgsstringreplacement
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.html
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:'})
pyqgis pyqgis-3 qgsstringreplacement
pyqgis pyqgis-3 qgsstringreplacement
edited 2 days ago
Kadir Şahbaz
4,60221531
4,60221531
asked Apr 5 at 2:21
GeorgeCGeorgeC
2,90132981
2,90132981
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
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:
To:
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
2 days ago
add a comment |
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}})
add a comment |
Your Answer
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "79"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f317855%2fsearch-and-replace-text-in-all-fields-in-qgis-3%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
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:
To:
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
2 days ago
add a comment |
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:
To:
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
2 days ago
add a comment |
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:
To:
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:
To:
edited 2 days ago
answered 2 days ago
BERABERA
17k62044
17k62044
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
2 days ago
add a comment |
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
2 days ago
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
2 days ago
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
2 days ago
add a comment |
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}})
add a comment |
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}})
add a comment |
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}})
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}})
answered 2 days ago
Kadir ŞahbazKadir Şahbaz
4,60221531
4,60221531
add a comment |
add a comment |
Thanks for contributing an answer to Geographic Information Systems Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f317855%2fsearch-and-replace-text-in-all-fields-in-qgis-3%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown