gpt4 book ai didi

Python3 : How to convert plain html into nested dictionary based on level of `h` tags?

转载 作者:行者123 更新时间:2023-12-01 00:06:41 27 4
gpt4 key购买 nike

我有一个如下所示的 html:

<h1>Sanctuary Verses</h1>
<h2>Purpose and Importance of the Sanctuary</h2>
<p>Ps 73:17\nUntil I went into the sanctuary of God; [then] understood I their end.</p>
<p>...</p>
<h2>Some other title</h2>
<p>...</p>
<h3>sub-sub-title</h3>
<p>sub-sub-content</p>
<h2>Some different title</h2>
<p>...</p>...

没有将 p 标记分组的 divsection 标记。它非常适合显示目的。我想提取数据以获得所需的输出。

期望的输出:

  1. h 标签应显示为标题并根据其级别嵌套
  2. p 标签应添加到 h 标签指定的特定标题下的内容

所需输出:

{
"title": "Sanctuary Verses"
"contents": [
{"title": "Purpose and Importance of the Sanctuary"
"contents":["Ps 73:17\nUntil I went into the sanctuary of God; [then] understood I their end.",
"...."
]
},
{"title": "Some other title"
"contents": ["...",
{"title": "sub-sub-title"
"content": ["sub-sub-content"]
}
]
},
{"title": "Some different title"
"content": ["...","..."]
}
}

我编写了一些解决方法代码来帮助我获得所需的输出。我想知道哪种方法是获得所需输出的最简单方法

最佳答案

这是一种堆栈问题/图问题。我们称它为一棵树吧。 (或文件或其他任何东西。)

我认为你的初始元组可以改进。 (文本、深度、类型)

stack = []
depth = 0
broken_value = -1
current = {"title":"root", "contents":[]}
for item in list_of_tuples:
if item[1]>depth:
#deeper
next = { "title":item[0], "contents":[] }
current["contents"].append(next)
stack.append(current)
current=next
depth = item[1]
elif item[1]<depth:
#shallower closes current gets previous level
while depth>item[1]:
prev = stack.pop()
depth = depth-1
current = {"title":item[0], "content":[]}
stack[-1].append(current)
depth=item[1]
else:
#same depth
if item[2]==broken_value:
#<p> element gets added to current level.
current['contents'].append(item[0])
else:
#<h> element gets added to parent of current.
current = {"title":item[0], "content":[]}
stack[-1]["contents"].append(current)
broken_value = item[2]

这将创建一个任意深度图,假设深度增加 1,但可以减少任意数量。

最好跟踪字典中的深度,以便一次可以移动多个深度。不仅仅是“标题”和“内容”,还可以是“标题”、“深度”和“内容”

说明
堆栈跟踪打开的元素,当前元素是我们正在构建的元素。

如果我们发现深度>大于当前深度,那么我们将当前元素放入堆栈(它仍然是打开的)并开始处理下一级元素。

如果深度小于当前元素,我们会将当前元素和父元素关闭到相同的深度。

最后,如果深度相同,我们决定它是刚刚添加的“p”元素,还是关闭当前并开始新当前的另一个“h”元素。

关于Python3 : How to convert plain html into nested dictionary based on level of `h` tags?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59929011/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com