Python 在嵌套字典中正确放置列表项
我有一个文本块列表,如下所示:Python 在嵌套字典中正确放置列表项,python,Python,我有一个文本块列表,如下所示: blocks = [ "created may 27th", "Introduction Foo Bar Bar", "Lorem te Ipsum", "Method Participants Foo Foo Bar Procedure Baz" ] 以及以下字典: structure = { "text": [],
blocks = [
"created may 27th",
"Introduction Foo Bar Bar",
"Lorem te Ipsum",
"Method Participants Foo Foo Bar Procedure Baz"
]
以及以下字典:
structure = {
"text": [],
"Introduction" : {
"text": []
},
"Method": {
"Participants" : {
"text": []
},
"Procedure": {
"text": []
}
}
}
我希望将两者结合起来,以便根据出现顺序和开头可能的标题字符串,文本块最终位于正确的位置,从而创建以下结构:
structure = {
"text": ["created may 27th"]
"Introduction" : {
"text": ["Foo Bar Bar", "Lorem te Ipsum"]
}
"Method": {
"Participants" {
"text": ["Foo Foo Bar"]
},
"Procedure": {
"text": ["Baz"]
}
}
这应该适用于任何长度的列表,以及任何深度的词典
我的直觉告诉我在文本块中循环,然后通过检查是否block.startswith(header)
,递归地找到它的位置,如果是,则拆分标题并使用文本块的右分区重复,否则追加到当前选择的“text”值。对我来说,最大的挑战是让2个for循环遍历文本块和字典项,同时跟踪字典中的位置,并在意味着返回到树中时能够移动到下一项
这就是我尝试过的:
def add_块(块,当前_节,标题_索引=0):
header=列表(当前节.keys())[header\u索引]
如果不是block.strip().startswith(标题):
当前_节['text']。追加(块)
elif块。起始带(标题):
block=block.partition(头)[-1]
添加_块(块,当前_节[页眉],页眉_索引+1)
对于块中的块:
添加_块(块、结构)
给定未受约束的键/项的长度,在尝试分配到结构之前,最好将列表“块”分解为子列表
subLists = {'text':[], 'intro':[], 'method':[]}
posits = ["text", "intro", "method"]
positSwitches = ['Introduction', 'Method', "###"] #Last entry is just an impossible string so we don't go out of range.
iPosits = 0
for line in blocks:
if left(line[:len(positSwitches[iPosits)] == positSwitches[iPosits]:
#We are at first line of a new entry, i.e. moving from text to intro
iPosits = iPosits + 1
subLists[posits[iPosits]].append(line)
上面应该给我们一个字典,它将列表“块”分为3个列表,每个列表项。由此,您可以为填充结构分配单独的函数。不幸的是,未经测试,我必须跑步——但希望能成为我工作的基础 列表“块”是否总是4个条目长,或者导言是否可以跨越多个列表条目?(而不仅仅是这两个)@Amiga500字典键和列表项的深度和长度不受限制。/n标记是否重要,或者您可以不使用它们,首先从字典的所有深度获取所有键,然后按照..操作块。连接块中的所有项目并执行字符串操作…这应该work@sadbro不幸的是,这并不能解释字典不同级别中出现的重复键。