我在raw_data下面。
'''
Filter_Port table
type : filter_1
ports : [7d77a1b7-434b-47fd-b2aa-d3442b831205]
type : filter_2
ports : [95a67e8c-63f9-4efc-b6b1-c04d5df61578, e1fea65f-62a3-43e9-8c33-c0e44ac3c86a]
type : filter_2
ports : []
'''
我需要使用python将其转换为以下格式:
result = [(filter_1, ['7d77a1b7-434b-47fd-b2aa-d3442b831205']), (filter_2, ['95a67e8c-63f9-4efc-b6b1-c04d5df61578', 'e1fea65f-62a3-43e9-8c33-c0e44ac3c86a']), (filter_2, [])]
答案 0 :(得分:0)
datastring = '''
Filter_Port table
type : filter_1
ports : [7d77a1b7-434b-47fd-b2aa-d3442b831205]
type : filter_2
ports : [95a67e8c-63f9-4efc-b6b1-c04d5df61578, e1fea65f-62a3-43e9-8c33-c0e44ac3c86a]
type : filter_2
ports : []
'''
output = []
lines = datastring.split("\n")
type_ = None
ports = None
for line in lines:
if line.strip().startswith("type "):
type_ = line.split(":")[1].strip()
assert ports is None, "problem with data"
elif line.strip().startswith("ports "):
ports_str = line.split(":")[1].strip("[] ")
ports = [p.strip() for p in ports_str.split(",")]
assert type_ is not None, "problem with data"
output.append((type_, ports))
type_ = None
ports = None
print(output)