2 回答
TA贡献1777条经验 获得超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) '}
TA贡献1858条经验 获得超8个赞
这会从引号之间的文本中去除不需要的空间":
import re
f = open(r'raw.txt', 'r')
text = f.read()
f.close()
pattern = r'\[(.+?)\].+?:\s*"\s*(.+?)\s*"'
result = dict(re.findall(pattern, text, flags=re.DOTALL))
print(result)
# {'192.168.1.1': 'Ubuntu(Core)', '192.168.1.2': 'Ubuntu (Core)', '192.168.1.3': 'CentOS (Core)', '192.168.1.5': 'Red Hat(Core)', '192.168.1.6': 'CentOS (Core)'}
添加回答
举报