首页 > 解决方案 > 如何将我的“拆分”代码转换为正则表达式

问题描述

我有一个raw.txt在下面。

ok: [192.168.1.1] => {
    "OS": "Ubuntu(Core) "
}
ok: [192.168.1.2] => {
    "OS": "Ubuntu (Core) "  
}
ok: [192.168.1.3] => {
    "OS": "CentOS (Core) "
}
ok: [192.168.1.3] => {
    "OS":"CentOS (Core) "  
}
ok: [192.168.1.5] => {
    "OS": "Red Hat(Core) "
}
ok: [192.168.1.6] => {
    "OS": "CentOS (Core) "  
}

我的 Python 代码如下所示如何转换为可取的输出

f = open(r'raw.txt', 'r')
s = f.read()
list1 = s.split('\n')
ip_list = []
os_list = []
for i in list1[::3]:
    ip_list.append(i)
for i in list1[1::3]:
    os_list.append(i)
y = [z[10:25] for z in os_list]
os_l = [x.strip(' ').replace('"','').replace(' ','') for x in y]
ip_l = [z[5:18] for z in ip_list]
ip_l_rep = [x.strip(' ').replace(']','') for x in ip_l]
{ip_l_rep[n]:os_l[n] for n in range(len(os_l))}

我的输出和预期低于

{'192.168.1.1': 'Ubuntu(Core)',
 '192.168.1.2': 'Ubuntu(Core)',
 '192.168.1.3': 'CentOS(Core)',
 '192.168.1.5': 'RedHat(Core)',
 '192.168.1.6': 'CentOS(Core)'}

由于在这个程序中使用了多个操作,我决定在正则表达式的帮助下编写。我写了一些伪代码但没有成功。喜欢提取\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}.

我的代码的任何增强也很感激

标签: pythonregexlistdictionary

解决方案


您可以使用正则表达式来捕获介于之间[]和之后的内容"OS": "

import re
input = """
ok: [192.168.1.1] => {
    "OS": "Ubuntu(Core) "
}
ok: [192.168.1.2] => {
    "OS": "Ubuntu (Core) "
}
ok: [192.168.1.3] => {
    "OS": "CentOS (Core) "
}
ok: [192.168.1.3] => {
    "OS":"CentOS (Core) "
}
ok: [192.168.1.5] => {
    "OS": "Red Hat(Core) "
}
ok: [192.168.1.6] => {
    "OS": "CentOS (Core) "
}
"""
items = re.findall(r'\[(.*?)\].*?"OS": "(.*?)"', input, flags=re.S)
data = dict(items)  # only works as you have 2 items (IP, OSTYPE)

print(data)
# output: {'192.168.1.1': 'Ubuntu(Core) ', '192.168.1.2': 'Ubuntu (Core) ', '192.168.1.3': 'Red Hat(Core) ', '192.168.1.6': 'CentOS (Core) '}

推荐阅读