python - 如何将我的“拆分”代码转换为正则表达式
问题描述
我有一个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}
.
我的代码的任何增强也很感激
解决方案
您可以使用正则表达式来捕获介于之间[]
和之后的内容"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) '}
推荐阅读
- ibm-cloud-infrastructure - 如何在安装后脚本中测试设备是裸机还是 VSI
- python - 从网站抓取数据到熊猫数据框
- google-analytics - Google Analytics:哪些域正在发送数据
- reactjs - REACT 如何使用 google-map-react 绘制路线?
- google-cloud-platform - 用户无法记住谷歌控制台登录详细信息
- highcharts - 从公共数据(json)中获取Highchart(/Highstock)
- android - 启动隐形活动以获取服务权限
- ios - ios:我需要填充一半的 UIImage
- javascript - React props 无法编译为属性值
- swift - 自定义 UITableView 内的 UITextField 在 Swift 中为零