gpt4 book ai didi

python - RegEx 将文本字符串拆分为 dict 作为组

转载 作者:太空宇宙 更新时间:2023-11-03 11:48:24 26 4
gpt4 key购买 nike

我正在尝试 RegEx 字符串输出并将其作为文本组添加到字典中,为此我正在使用 re.split()

我的字符串输出是:

mpathag (36005076801b2014804000000000001cd) dm-7 Test ,2145
size=488G features='1 queue_if_no_path' hwhandler='0' wp=rw
|-+- policy='service-time 0' prio=50 status=active
| |- 12:0:1:3 sdas 66:192 active ready running
| `- 13:0:1:3 sdbi 67:192 active ready running
`-+- policy='service-time 0' prio=10 status=enabled
|- 12:0:0:3 sdak 66:64 active ready running
`- 13:0:0:3 sdba 67:64 active ready running
mpathz (36005076801b2014804000000000001c4) dm-0 Test ,2145
size=488G features='1 queue_if_no_path' hwhandler='0' wp=rw
|-+- policy='service-time 0' prio=50 status=active
| |- 12:0:0:0 sdah 66:16 active ready running
| `- 13:0:0:0 sdax 67:16 active ready running
`-+- policy='service-time 0' prio=10 status=enabled
|- 10:0:0:0 sdb 8:16 active ready running
`- 13:0:1:0 sdbf 67:144 active ready running

这里是我的解析代码:

    output = "mpathag (36005076801b2014804000000000001cd) dm-7 Test ,2145\
size=488G features='1 queue_if_no_path' hwhandler='0' wp=rw\
|-+- policy='service-time 0' prio=50 status=active\
| |- 12:0:1:3 sdas 66:192 active ready running\
| `- 13:0:1:3 sdbi 67:192 active ready running\
`-+- policy='service-time 0' prio=10 status=enabled\
|- 12:0:0:3 sdak 66:64 active ready running\
`- 13:0:0:3 sdba 67:64 active ready running\
mpathz (36005076801b2014804000000000001c4) dm-0 Test ,2145\
size=488G features='1 queue_if_no_path' hwhandler='0' wp=rw\
|-+- policy='service-time 0' prio=50 status=active\
| |- 12:0:0:0 sdah 66:16 active ready running\
| `- 13:0:0:0 sdax 67:16 active ready running\
`-+- policy='service-time 0' prio=10 status=enabled\
|- 10:0:0:0 sdb 8:16 active ready running\
`- 13:0:1:0 sdbf 67:144 active ready running"

devices = re.split('mpath', output)
for dev in devices:
print dev

我的问题是 re.split 从文本中删除了模式是否可以在不删除分隔符的情况下进行拆分?

输出结果是这样的:

ag (36005076801b2014804000000000001cd) dm-7 Test ,2145    
size=488G features='1 queue_if_no_path' hwhandler='0' wp=rw
|-+- policy='service-time 0' prio=50 status=active
| |- 12:0:1:3 sdas 66:192 active ready running
| `- 13:0:1:3 sdbi 67:192 active ready running
`-+- policy='service-time 0' prio=10 status=enabled
|- 12:0:0:3 sdak 66:64 active ready running
`- 13:0:0:3 sdba 67:64 active ready running

最佳答案

如果模式包含捕获组,则不会排除该组:

>>> re.split(',', '1,2,3')  # without capturing group
['1', '2', '3']
>>> re.split('(,)', '1,2,3') # with capturing group
['1', ',', '2', ',', '3']
>>> xs = re.split('(,)', '1,2,3')
>>> [part1+part2 for part1, part2 in zip(xs[1::2], xs[2::2])]
[',2', ',3']

devices = re.split('(mpath)', output)
for part1, part2 in zip(devices[1::2], devices[2::2]):
print part1 + part2

关于python - RegEx 将文本字符串拆分为 dict 作为组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33776133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com