gpt4 book ai didi

python 如何从该文件形成字典

转载 作者:行者123 更新时间:2023-11-30 22:14:12 25 4
gpt4 key购买 nike

需要一点帮助。我有一个大文件,主要包含下面屏幕截图中的行。以字符串“zone”开头的每个 block 之间有空行。

如何形成字典,以便 test_1、test_2 和 test_3 是我的键,我的值是所有行直到空行?

第一个键的示例

键= test_1

值 = ['* fcid 0x170024 [pwwn 10:00:00:00:c9:5f:84:93] [xxxx]','* fcid 0x170016 [pwwn 50:06:0e:80:16:60 :ef:43] [xxxxxxxxx]']

有什么好的建议吗?提前致谢

enter image description here

正文如下:

zone name test_1 vsan xx

* fcid 0x170024 [pwwn 10:00:00:00:c9:5f:84:93] [xxx]
* fcid 0x170016 [pwwn 50:06:0e:80:16:60:ef:43] [xxxxxx]

zone name test_2 vsan xx

* fcid 0x170024 [pwwn 10:00:00:00:c9:5f:84:93] [xx]
* fcid 0x170017 [pwwn 50:06:0e:80:16:60:ef:63] [xxx]

zone name test_2 vsan yy

pwwn 10:00:00:90:fa:81:bb:f2
* fcid 0x0b00c0 [pwwn 50:06:0e:80:07:e6:2e:26]

最佳答案

您可以将正向先行断言与正则表达式结合使用。

尝试(?m)^zone\sname\s(\w+).*([\s\S]*?)(?=[\n\r]+zone\sname\s|\Z)

在行动

import re

pattern = r'(?m)^zone\sname\s(\w+).*([\s\S]*?)(?=[\n\r]+zone\sname\s|\Z)'

with open('test.txt') as f:
data = {k: [
i for i in v.split('\n') if i
] for k, v in dict(re.findall(pattern, f.read())).items()}

print(data)

结果:

{'test_1': ['* fcid 0x170024 [pwwn 10:00:00:00:c9:5f:84:93] [xxx]', '* fcid 0x170016 [pwwn 50:06:0e:80:16:60:ef:43] [xxxxxx]'], 'test_2': ['* fcid 0x170024 [pwwn 10:00:00:00:c9:5f:84:93] [xx]', '* fcid 0x170017 [pwwn 50:06:0e:80:16:60:ef:63] [xxx]'], 'test_3': ['pwwn 10:00:00:90:fa:81:bb:f2', '* fcid 0x0b00c0 [pwwn 50:06:0e:80:07:e6:2e:26]']}

正则表达式说明:

(?m)                             # asserts multiline matching
^zone\sname\s # matches zone name at start of line
( # matching group 1
\w+ # Matches your key
)
.* # Matches any character but new line
( # Matching group 2
[\s\S]*? # Matches until...
)
(?= # ... this group is found
[\n\r]+
zone\sname # same as first match
\s
| # or
\Z # end of string
)

关于python 如何从该文件形成字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50592769/

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