gpt4 book ai didi

python - 使用正则表达式将多行脚本输出转换为字典

转载 作者:行者123 更新时间:2023-12-01 04:39:49 25 4
gpt4 key购买 nike

我得到以下脚本输出:

***************************************************
[g4u2680c]: searching for domains
---------------------------------------------------
host = g4u2680c.houston.example.com
ipaddr = [16.208.16.72]
VLAN = [352]
Gateway= [16.208.16.1]
Subnet = [255.255.248.0]
Subnet = [255.255.248.0]
Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c]

host = g4u2680c.houston.example.com
ipaddr = [16.208.16.72]
VLAN = [352]
Gateway= [16.208.16.1]
Subnet = [255.255.248.0]
Subnet = [255.255.248.0]
Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c]

* script completed Mon Jun 15 06:13:14 UTC 2015 **
* sleeping 30 to avoid DOS on dns via a loop **
<小时/>

我需要将 2 个主机列表提取到字典中,不带括号。

这是我的代码:

#!/bin/env python

import re

text="""***************************************************
[g4u2680c]: searching for domains
---------------------------------------------------
host = g4u2680c.houston.example.com
ipaddr = [16.208.16.72]
VLAN = [352]
Gateway= [16.208.16.1]
Subnet = [255.255.248.0]
Subnet = [255.255.248.0]
Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c]

host = g4u2680c.houston.example.com
ipaddr = [16.208.16.72]
VLAN = [352]
Gateway= [16.208.16.1]
Subnet = [255.255.248.0]
Subnet = [255.255.248.0]
Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c]

* script completed Mon Jun 15 06:13:14 UTC 2015 **
* sleeping 30 to avoid DOS on dns via a loop **
***************************************************
"""

seq = re.compile(r"host.+?\n\n",re.DOTALL)

a=seq.findall(text)

matches = re.findall(r'\w.+=.+', a[0])

matches = [m.split('=', 1) for m in matches]

matches = [ [m[0].strip().lower(), m[1].strip().lower()] for m in matches]

#should have function with regular expression to remove bracket here

d = dict(matches)

print d

到目前为止我对第一个主机的了解:

{'subnet': '[255.255.248.0]', 'vlan': '[352]', 'ipaddr': '[16.208.16.72]', 'cluster': '[g4u2679c g4u2680c g9u1484c g9u1485c]', 'host': 'g4u2680c.houston.example.com', 'gateway': '[16.208.16.1]'}

我需要帮助找到正则表达式来删除括号,因为字典中的值包含带括号和不带括号的数据。

或者是否有更好更简单的方法将原始脚本输出转换为字典。

最佳答案

您可以使用: (\w+)\s*=\s*\[?([^\n\]]+)\]?

demo

import re
p = re.compile(ur'(\w+)\s*=\s*\[?([^\n\]]+)\]?', re.MULTILINE)
test_str = u"host = g4u2680c.houston.example.com\n ipaddr = [16.208.16.72]\n VLAN = [352]\n Gateway= [16.208.16.1]\n Subnet = [255.255.248.0]\n Subnet = [255.255.248.0]\n Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c]\n\nhost = g4u2680c.houston.example.com\n ipaddr = [16.208.16.72]\n VLAN = [352]\n Gateway= [16.208.16.1]\n Subnet = [255.255.248.0]\n Subnet = [255.255.248.0]\n Cluster= [g4u2679c g4u2680c g9u1484c g9u1485c]\n"

re.findall(p, test_str)

关于python - 使用正则表达式将多行脚本输出转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30963604/

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