使用ArcGIS Pro在字段计算器中查找子字符串

在ArcGIS Pro 2.4中,我有一个相当简单的操作失败了,而且我一生也无法弄清原因。

如果字段“ assettype”包含搜索字符串的一部分,则将assettype_groupup的值设置为我返回的值。

例如,如果“ assetttype”包含字符串“ Building | Residential | Large”,并且我测试它是否包含术语“ Residential”,并且其值为true,则返回字符串“ Residential”。

当前代码似乎没有返回任何结果/没有任何效果,并且似乎运行得太快(3,000,000行需要2-3秒)。

如果我尝试三元声明,这意味着一次使用一个术语,这似乎就很好了。我宁愿不采用这种方法,因为if / elif可能性本质上会变得很广泛,并且我只想运行一次例程。

您能否看到下面的设置有任何明显的问题

#Target Field Name 
assettype_groupup

#Expression
func(!assettype!)

# Code block
def func(input):
    if 'Residential' in input:
        return 'Residential'
    elif 'Industrial/Utilities' in input:
        return 'Industrial/Utilities'
    elif 'Transport/Infrastructure' in input:
        return 'Transport/Infrastructure'
    elif 'Conservation/National Park' in input:
        return 'Conservation/National Park'
    elif 'Recreational/Open Space' in input:
        return 'Recreational/Open Space'
    elif 'Mixed Use' in input:
        return 'Mixed Use'
    elif 'Community Use' in input:
        return 'Community Use'
    elif 'Rural/Primary Production' in input:
        return 'Rural/Primary Production'
    elif 'Special Use' in input:
        return 'Special Use'
    elif 'Unknown' in input:
        return 'Unknown'
    else:
        ''
HELLO_JAVA521 回答:使用ArcGIS Pro在字段计算器中查找子字符串

我对ArcGIS Pro并不熟悉,但是对Python的了解却很深。

在Python中,应避免将变量或参数命名为与任何变量相同的名称 内置函数,而input()是内置函数的名称。另外,之后的行 最后的else:应该是return ''。既然不是这样,您的 如果没有匹配项,不是该函数,该函数将有效地返回None 空字符串''(假设您就是这个意思)。

请记住,以下是编写避免上述两个问题的函数的更好方法:

TARGETS = (
    'Residential','Industrial/Utilities','Transport/Infrastructure','Conservation/National Park','Recreational/Open Space','Mixed Use','Community Use','Rural/Primary Production','Special Use','Unknown',)


# Code block
def func(info):
    for target in TARGETS:
        if target in info:
            return target
    else:  # Nothing matched.
        return ''

一种更高级,更短并且可能更快的方法是使用Python的re正则表达式模块,该模块是其标准库的一部分:

import re

regex = re.compile('|'.join(map(re.escape,TARGETS)))

# Code block
def func(info):
    mo = regex.search(info)
    return mo.group(0) if mo else ''

在Python 3.8.0+中,可以使用:=(又称“海象”运算符)为PEP 572's使用assignment expressions新语法,从而将其缩短一些时间。从该版本开始添加:

import re

regex = re.compile('|'.join(map(re.escape,TARGETS)))

def func(info):
    return mo.group(0) if (mo := regex.search(info)) else ''  # Py 3.8.0+
本文链接:https://www.f2er.com/3004517.html

大家都在问