【发布时间】:2021-01-07 15:36:43
【问题描述】:
我正在自学 Python (2.7) for ArcGIS (10.8)。我有这个问题:
编写一个脚本,将文本字段添加到名为 road.shp 的要素类中 FERRY 并使用 YES 和 NO 值填充此字段,具体取决于 FEATURE 字段的值。
在尝试弄清楚并通过互联网检查后,我得到了这个脚本:
from arcpy
from arcpy import env
env.workspace = "C/esriPress/Python/Data/Exercise07/Results" # Set workspace
env.overwriteOutput = True # overwriting outputs
fc = "roads.shp" # input feature class
newfield = "FERRY" # new field to be created
fieldtype = "TEXT" # type of the field that is going to be created
fieldname = arcpy.ValidateFieldName(newfield) # to determine whether a specific name is valid or not
field_length = 3 # Lenght of th new field to be created
fieldlist = ListFields(fc) # list the fields in 'fc', it returns a reference number of each object, not the object name.
fieldnames = [] # Create an empty list
# Check whether 'newfield' already exist or not; if not, create it
for field in fieldlist: # For each element in 'fieldlist'...
fieldnames.append(field.name) #...add in the empty list 'fieldnames' the field name
if fieldname not in fieldnames: # if 'fieldname' don't exists in 'fiednames'...
arcpy.AddField_management(fc, fieldname, fieldtype, field_length) # ...Create 'fieldname' in 'fc' with length = 3
print ("New field has been added")
else:
print ("Field name already exists.")
# Search in the one field and update other field
fields = ['FEATURE', newfield] # Create a list that contains the field we apply condition, and the field we going to update
with arcpy.da.UpdateCursor(fc, fields) as cursor: # Setting the cursor; notice the cursor is made up of two fields
for row in cursor: # For each row in cursor...
if row[0] == "Ferry Crossing": #...if row in field 1 = "Ferry Crossing'...
row[1] = "YES" #... Set that row in field 2 to 'Yes'
else: # Otherwise...
row[1] = "NO" # ....Set that row in field 2 to 'No'...
cursor.updateRow(row) # Update cursor
print ("New field has been added" % newfield)
else:
row[1] = "NO"
cursor.updateRow(row)
print ("Field name already exists" % newfield)
但是,当我在 PythonWin 2.7.16 中运行脚本时,我收到以下错误消息:
Failed to run script - syntax error - invalid syntax
我的脚本有什么问题?这是正确的方法吗?
【问题讨论】: