我已经创建了一个示例 python 脚本来完成这项工作,你可以随意调整它。它将您的格式转换为嵌套的字典。动态随心所欲。
看看这里:Paste bin
代码:
import re
import ast
data = """ { Countries = { USA = 1; "Connections" = { "1 Flights" = 0; "10 Flights" = 0; "11 Flights" = 0; "12 Flights" = 0; "13 Flights" = 0; "14 Flights" = 0; "15 Flights" = 0; "16 Flights" = 0; "17 Flights" = 0; "18 Flights" = 0; "More than 25 Flights" = 0; }; "Single Connections" = 0; "No Connections" = 0; "Delayed" = 0; "Technical Fault" = 0; "Others" = 0; }; }"""
def arrify(string):
string = string.replace("=", " : ")
string = string.replace(";", " , ")
string = string.replace("\"", "")
stringDict = string.split()
# print stringDict
newArr = []
quoteCosed = True
for i, splitStr in enumerate(stringDict):
if i > 0:
# print newArr
if not isDelim(splitStr):
if isDelim(newArr[i-1]) and quoteCosed:
splitStr = "\"" + splitStr
quoteCosed = False
if isDelim(stringDict[i+1]) and not quoteCosed:
splitStr += "\""
quoteCosed = True
newArr.append(splitStr)
newString = " ".join(newArr)
newDict = ast.literal_eval(newString)
return normalizeDict(newDict)
def isDelim(string):
return str(string) in "{:,}"
def normalizeDict(dic):
for key, value in dic.items():
if type(value) is dict:
dic[key] = normalizeDict(value)
continue
dic[key] = normalize(value)
return dic
def normalize(string):
try:
return int(string)
except:
return string
print arrify(data)
样本数据的结果:
{'Countries': {'USA': 1, 'Technical Fault': 0, 'No Connections': 0, 'Delayed': 0, 'Connections': {'17 Flights': 0, '10 Flights': 0, '11 Flights': 0, 'More than 25 Flights': 0, '14 Flights': 0, '15 Flights': 0, '12 Flights': 0, '18 Flights': 0, '16 Flights': 0, '1 Flights': 0, '13 Flights': 0}, 'Single Connections': 0, 'Others': 0}}
你可以像普通的 dict 一样获得值 :) 希望它有所帮助......