我意识到这是帖子的常见主题,但是,我似乎无法找到一个真正帮助我解决问题的例子。我正在尝试运行一个脚本,它将向shapefile添加两个新字段(x和y coords),然后使用代码块用X和Y coords填充这些字段。这适用于AcrGIS 10.2.2,但我不认为问题是ArcGIS问题。下面的脚本:
# Add new fields for "New_X" and "New_Y" for new points to be added
# Calculate values for those new fields based on distance along line
import arcpy, arcpy.mapping
from arcpy import env
env.workspace = r"G:\Geocomputation_Project\Section_C\Model_Shapes"
env.overwriteOutput = True
# Set local Variables
in_table = 'Points.shp'
field_x = 'New_X'
field_y = 'New_Y'
expression = "getXY(!Shape!, !ITEMID!, !CHAINAGE!)"
code_block_x = """def getXY (point, id, d2add):
mxd = arcpy.mapping.MapDocument("G:\Geocomputation_Project\Section_C\Model_Shapes\Geocomputation_Project.mxd")
lyr=arcpy.mapping.ListLayers(mxd,"LINES")[0]
q='"ITEMID"=%s%s%s' %(r"'",id,"'")
pNew = 0
with arcpy.da.SearchCursor(lyr,"Shape@",q)as cursor:
for row in cursor:
line=row[0];break
pointPos=line.measureOnLine(point)+d2add
pNew+=line.positionAlongLine(pointPos).firstPoint
pNew.X"""
code_block_y = """def getXY (point, id, d2add):
mxd = arcpy.mapping.MapDocument("G:\Geocomputation_Project\Section_C\Model_Shapes\Geocomputation_Project.mxd")
lyr=arcpy.mapping.ListLayers(mxd,"LINES")[0]
q='"ITEMID"=%s%s%s' %(r"'",id,"'")
pNew = 0
with arcpy.da.SearchCursor(lyr,"Shape@",q)as cursor:
for row in cursor:
line=row[0];break
pointPos=line.measureOnLine(point)+d2add
pNew+=line.positionAlongLine(pointPos).firstPoint
pNew.Y"""
# Execute AddField for each new X and Y coord
arcpy.AddField_management(in_table, field_x, "Double")
arcpy.AddField_management(in_table, field_y, "Double")
# Execute CalculateField to each new X and Y field
arcpy.CalculateField_management(in_table, field_x, expression, "PYTHON_9.3", code_block_x)
arcpy.CalculateField_management(in_table, field_y, expression, "PYTHON_9.3", code_block_y)
我一直得到AttributeError:'int'对象没有属性'X'。
答案 0 :(得分:0)
假设标题中的错误是正确的,而不是帖子正文中的错误,那么这就是您的问题:
pNew = 0
# ...
pNew.Y
很明显,这不会起作用
答案 1 :(得分:0)
我现在知道了,似乎还有更多的语法/缩进错误。还需要“返回”pNew变量。见下面的工作脚本:
code_block_x = """def getXY (point, id, d2add):
mxd = arcpy.mapping.MapDocument("G:\Geocomputation_Project\Section_C\Model_Shapes\Geocomputation_Project.mxd")
lyr=arcpy.mapping.ListLayers(mxd,"LINES")[0]
q='"ITEMID"=%s%s%s' %(r"'",id,"'")
with arcpy.da.SearchCursor(lyr,"Shape@",q)as cursor:
for row in cursor:
line=row[0];break
pointPos=line.measureOnLine(point)+d2add
pNew=line.positionAlongLine(pointPos).firstPoint
return pNew.X"""
和
code_block_y = """def getXY (point, id, d2add):
mxd = arcpy.mapping.MapDocument("G:\Geocomputation_Project\Section_C\Model_Shapes\Geocomputation_Project.mxd")
lyr=arcpy.mapping.ListLayers(mxd,"LINES")[0]
q='"ITEMID"=%s%s%s' %(r"'",id,"'")
with arcpy.da.SearchCursor(lyr,"Shape@",q)as cursor:
for row in cursor:
line=row[0];break
pointPos=line.measureOnLine(point)+d2add
pNew=line.positionAlongLine(pointPos).firstPoint
return pNew.Y"""