我已经创建了一个示例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}}
,你可以得到像一个正常的字典值将:)希望它帮助...
来源
2016-02-29 10:14:16
rrw
你确实需要在你的答案中包含代码。只是连接到它是不够的。 – Blckknght
@richmondwang,正是我在找的东西。然而,这次我的动态字符串如下,这给了我一个语法错误: – user2605278
你传递了什么数据? @ user2605278 – rrw