Friday 15 June 2018

python - selecting by attribute and specific value replace


I want to select all of the features by attribute where the attribue in myattrib is like...


Selection "criteria H". That is not a problem.


However then I need to replace (myattrib," H", "") except I only want to replace the H at the end of the attribute, not within, like "toast is Hot H".


In this record I want the value to end up as "toast is HotH"


There are 15k records but only 4800 have the value I am replacing. And it is always the same value.


edit response:


No. All values I want to fix end in H with a space in front of it. I am depending on search replace but not sure how to leave the space in front of Hot.



In my example I am able to select with the "% H" which specifies there is nothing after the H so the select won't get Hot even though there is a space before it. However when it comes to replace it does a literal replace on " H" and doesn't care about the ot.


I think if I knew some regex and "IF" arcmap supports that, It might do the trick (from what I have seen on the FMEtalk forum). I'm sure someone can talk me through this.



Answer



Yes Regular expressions are probably the best way to do this, and yes you can use regular expressions in the Calculate Field tool


First the regular expression


>>> import re
>>> val = 'National and Provincial capital'
>>> print re.sub('al$', 'X', val)
National and Provincial capitX


I'm subsituting "a" followed by "l" followed by "$" (which means the end of the sting) with the string 'X'. So 'capital' becomes 'capiX', while 'National' and 'Provincial' are unchanged.


Now use this same logic inside the code block for CalculateField. Set the calculateField parameters as follows -'Field Name" param to the output field name (i recommend calc'ing into a new field at least until you're sure the output is correct).


-'Expression' param to this


myroutine(!my_input_field_name!)



  • 'Expressioin Type' param to PYTHON





  • 'Code block' param to this




.


import re
def myroutine(val):
return re.sub('al$', 'X', val)

Some docs if you want to read up.




No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...