Use Cursor to Update Field

المشرف العام

Administrator
طاقم الإدارة
I have a script tool that truncates each word in field to 3 characters and outputs the result in a new field:

"THIS IS AN EXAMPLE STRING" becomes "THI IS AN EXA STR"

import arcpyarcpy.env.overwriteOutput = True# Prelogic used to pass through for calculating truncated name valuescodeblock = """def nmshort(stname): s = stname.split() s2 = s[:] = [elem[:3] for elem in s] return ' '.join(s2)""" # Finished code blocktry: # Set input parameters inFC = arcpy.GetParameterAsText(0) inName = arcpy.GetParameterAsText(1) inNameShort = arcpy.GetParameterAsText(2) # set expression for field calculation to variables expression = "nmshort(!{0}!)".format(inName) # perform field calculation arcpy.AddMessage("Calculating truncated strings for values in input name field") arcpy.CalculateField_management(inFC, inNameShort, expression, "PYTHON_9.3", codeblock) arcpy.AddMessage("Calculation complete")except: arcpy.AddError("Could not complete the calculation") arcpy.AddMessage(arcpy.GetMessages())It works fine except I want to make a parameter in the tool that will allow the user to specify the length for truncation instead of a constant of 3. With having to pass the codeblock to calculatefield as a string, I'm struggling to figure out how to pass the length parameter to a variable in the codeblock. Most of the time the length will be either 3 or 4, so I suppose I could create two blocks of code: one to run if the length parameter is 3 and another if 4. That would be the easy way out though and I want to learn (I'm a noob). I'm really interested in doing this with an update cursor, if it can be done that way. I've played with cursors with some success with simpler calculations. I can't figure out how to write the more advanced logic involved in this calculation though.

I'm using ArcGIS 10.0 so I can't use the data access cursors. I have a more complex one after this, but I'm hoping I can learn enough from this example to be more self reliant on that one. Also, I can't tell you the resource this site has been.



أكثر...
 
أعلى