解析以反斜杠分隔的层次结构路径(不同级别数)

Parse backslash-delimited hierarchy path (varying number of levels)

我的层次结构路径具有不同级别(最多 4 个):

FACILITIES \ PARK
ROADS \ GRASS/TURF BLVD MAINTENANCE
ROADS \ SIDEWALKS \ REPLACEMENT
FACILITIES \ PARKING - MAIN ST
RECREATION \ BANDSHELL \ PROPERTY \ BUILDING-GENERAL
FACILITIES \ FIREHALL \ PLUMBING
FACILITIES

我想解析 _\_ 定界符处的级别并将值插入到 Maximo 数据库列中:

(这些列的长度现在只有 10。稍后我会创建适当的自定义列,长度更长。)


我尝试过的:

我已经弄清楚如何解析级别并将值插入列中 — IF(这是一个很大的 IF)总有 4 个级别:

#Auto-script on WORKORDER
h = mbo.getString("HIERARCHYPATH")
mbo.setValue("WOEQ1", (h.split(' \ '))[0][:10])
mbo.setValue("WOEQ2", (h.split(' \ '))[1][:10])
mbo.setValue("WOEQ3", (h.split(' \ '))[2][:10])
mbo.setValue("WOEQ4", (h.split(' \ '))[3][:10])

当然,我不会总是有 4 个级别。我可以在 1-4 之间设置任意数量的级别。


如何解析以反斜杠分隔的层次结构路径(具有不同数量的级别)?

您可以让“正常”拆分来划分您的行

>>> s = """\
... FACILITIES \ PARK
... ROADS \ GRASS/TURF BLVD MAINTENANCE
... ROADS \ SIDEWALKS \ REPLACEMENT
... FACILITIES \ PARKING - MAIN ST
... RECREATION \ BANDSHELL \ PROPERTY \ BUILDING-GENERAL
... FACILITIES \ FIREHALL \ PLUMBING
... FACILITIES
... """
>>> for row in s.splitlines():
...    print(row.split(" \ "))
...
['FACILITIES', 'PARK']
['ROADS', 'GRASS/TURF BLVD MAINTENANCE']
['ROADS', 'SIDEWALKS', 'REPLACEMENT']
['FACILITIES', 'PARKING - MAIN ST']
['RECREATION', 'BANDSHELL', 'PROPERTY', 'BUILDING-GENERAL']
['FACILITIES', 'FIREHALL', 'PLUMBING']
['FACILITIES']

然后您可以遍历返回的列表,设置每个值

max_col_length = 10  # to be updated by author
for row in s.splitlines():
    for index, atom in enumerate(row.split(" \ "), 1):  # count from 1
        mbo = "create a new row"  # not shown by author
        mbo.setValue("WOEQ{}".format(index), atom[:max_col_length])
    "INSERT row if processing rows individually"
"INSERT all rows if able to upload them all at the same time"

如果您需要始终在您的列表中提供至少 4(或 N)个成员,您可以使用itertools.repeat填写剩余的值

>>> import itertools
>>> mylist = ['RECREATION', 'BANDSHELL', 'PROPERTY']
>>> mylist.extend(list(itertools.repeat(None, 4 - len(mylist))))
>>> print(mylist)
['RECREATION', 'BANDSHELL', 'PROPERTY', None]

这是我最终使用的脚本(它是@ti7 答案的变体)。

脚本 nulls-out 新层次结构路径少于四个级别的场景中的现有值。

parts = s.split(r' \ ')
for i, part in enumerate(parts, 1):
    mbo.setValue(col_prefix + str(i), part)
for i in range(len(parts)+1, 5):
    mbo.setValueNull(col_prefix + str(i))