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)'}
添加回答
舉報