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

我有不同级别数(最多 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 数据库列中:


WOEQ1

WOEQ2

WOEQ3

WOEQ4

(这些列的长度现在只有 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 之间任意数量的级别。


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


陪伴而非守候
浏览 127回答 2
2回答

精慕HU

您可以让“正常”拆分来划分行>>> 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 authorfor 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 答案的变体)。在新的层次结构路径少于四个级别的情况下,脚本会将现有值清空。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))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python