基本上,我想遍历一个文件,并将每行的内容放入一个深层嵌套的字典中,其结构由多余的空格在每一行的开始。从python中的缩进文本文件创建树/深层嵌套字典
本质上的目的是采取这样的:
a
b
c
d
e
,并把它弄成这个样子:
{"a":{"b":"c","d":"e"}}
或者这样:
apple
colours
red
yellow
green
type
granny smith
price
0.10
到这一点:
{"apple":{"colours":["red","yellow","green"],"type":"granny smith","price":0.10}
这样我就可以将它发送到Python的JSON模块并制作一些JSON。
目前我正在试图让一个字典和像这样的步骤列表:
{"a":""} ["a"]
{"a":"b"} ["a"]
{"a":{"b":"c"}} ["a","b"]
{"a":{"b":{"c":"d"}}}} ["a","b","c"]
{"a":{"b":{"c":"d"},"e":""}} ["a","e"]
{"a":{"b":{"c":"d"},"e":"f"}} ["a","e"]
{"a":{"b":{"c":"d"},"e":{"f":"g"}}} ["a","e","f"]
等等
名单就像“面包屑”表示在我上次放在一个字典。
要做到这一点,我需要一种方法来遍历列表并生成类似dict["a"]["e"]["f"]
的东西来得到最后一个字典。我有一个看看类自动激活,有人做出了看起来非常有用但我真的不确定的:
- 无论我使用这个正确的数据结构(我打算送它到JSON库来创建一个JSON对象)
- 如何在这种情况下使用自动授权
- 是否有更好的方法来解决这个问题。
我想出了下面的功能,但它不工作:
def get_nested(dict,array,i):
if i != None:
i += 1
if array[i] in dict:
return get_nested(dict[array[i]],array)
else:
return dict
else:
i = 0
return get_nested(dict[array[i]],array)
将不胜感激帮助!
(我非常不完整的代码的其余部分是在这里:)
#Import relevant libraries
import codecs
import sys
#Functions
def stripped(str):
if tab_spaced:
return str.lstrip('\t').rstrip('\n\r')
else:
return str.lstrip().rstrip('\n\r')
def current_ws():
if whitespacing == 0 or not tab_spaced:
return len(line) - len(line.lstrip())
if tab_spaced:
return len(line) - len(line.lstrip('\t\n\r'))
def get_nested(adict,anarray,i):
if i != None:
i += 1
if anarray[i] in adict:
return get_nested(adict[anarray[i]],anarray)
else:
return adict
else:
i = 0
return get_nested(adict[anarray[i]],anarray)
#initialise variables
jsondict = {}
unclosed_tags = []
debug = []
vividfilename = 'simple.vivid'
# vividfilename = sys.argv[1]
if len(sys.argv)>2:
jsfilename = sys.argv[2]
else:
jsfilename = vividfilename.split('.')[0] + '.json'
whitespacing = 0
whitespace_array = [0,0]
tab_spaced = False
#open the file
with codecs.open(vividfilename,'rU', "utf-8-sig") as vividfile:
for line in vividfile:
#work out how many whitespaces at start
whitespace_array.append(current_ws())
#For first line with whitespace, work out the whitespacing (eg tab vs 4-space)
if whitespacing == 0 and whitespace_array[-1] > 0:
whitespacing = whitespace_array[-1]
if line[0] == '\t':
tab_spaced = True
#strip out whitespace at start and end
stripped_line = stripped(line)
if whitespace_array[-1] == 0:
jsondict[stripped_line] = ""
unclosed_tags.append(stripped_line)
if whitespace_array[-2] < whitespace_array[-1]:
oldnested = get_nested(jsondict,whitespace_array,None)
print oldnested
# jsondict.pop(unclosed_tags[-1])
# jsondict[unclosed_tags[-1]]={stripped_line:""}
# unclosed_tags.append(stripped_line)
print jsondict
print unclosed_tags
print jsondict
print unclosed_tags
我不得不引用[的Python禅](http://www.python.org/dev/peps/pep-0020/)“扁平比嵌套更好“。我会改变你如何做这件事。总比嵌套字典有更好的方法。此外,请确保你没有陷入[X Y问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 –
我最初的做法很简单,就是使用各种规则生成一个很长的字符串。那会更好吗? – Tomcat
这取决于你想要达到的目标,看看[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem),并确保你是不会犯类似的错误。本质上,你需要弄清楚你的数据是什么,并围绕它建立你的容器,而不是建立一个容器,并找出如何把你的数据放入它。每种类型的容器都有其优点,但使用字符串来存储不同的数据集从来都不是一个好主意。 –