python脚本中shp文件字段计算的问题

1 投票
3 回答
2231 浏览
提问于 2025-04-16 23:49

我添加了一个字段,想通过代码块来计算这个字段的值,但我觉得代码块没有正常工作。在输出的shp文件中,所有的值都显示为0。以下是我的代码:

# An input polygon feature class
inputFC = "D:/Delete/NewLineFeature.shp"

gp.AddField_management(inputFC, "lenclass", "SHORT")
# Calculation is based on a custom getclass definition
expression = "getclass(float(!shape.length!))"
codeblock = """\
def getclass(length):
if length <= 600.0:
return 1
if length > 600.0 and length <= 6000.0:
return 2
else:
return 3
"""
gp.CalculateField_management(inputFC, "lenclass", expression, "PYTHON", codeblock)`

3 个回答

0

Python使用空白字符来区分代码块,而你的字符串中没有这些空白字符。你可以试试这个:

codeblock = """\
def getclass(length):
    if length <= 600.0:
        return 1
    if length > 600.0 and length <= 6000.0:
        return 2
    else:
        return 3
"""
0

在Python中,三重引号的字符串会自动延续到下一行,直到遇到匹配的结束引号为止。不过,它们只会包含你给它们的空格部分。这可能会导致你的代码出现缩进问题。

2

在这个代码块中,缩进是用两个空格来表示的,这个是在计算字段工具的代码块里(arcgis 10)。

def getclass(length):
  if length <= 600.0:
    return 1
  if length > 600.0 and length <= 6000.0:
    return 2
  else:
    return 3

撰写回答