gpt4 book ai didi

python - 使用 lxml 合并来自两个段落的 HTML 内容

转载 作者:行者123 更新时间:2023-11-28 00:56:29 26 4
gpt4 key购买 nike

我想将两个段落中的所有内容合并为一个段落,并在它们之间留一个空格。我如何使用 lxml 执行此操作?

例子:

<p>He is <b>bold</b>!</p>
<p>Is he <u>here</u>?</p>

将合并到:

<p>He is <b>bold</b>! Is he <u>here</u>?</p>

最佳答案

如果您的结构很简单,这可能会成功:

import lxml
from lxml import etree

root = etree.fromstring("<root></root>")
first = etree.fromstring("<p>He is <b>bold</b>!</p>")
second = etree.fromstring("<p>Is he <u>here</u>?</p>")
try:
first.getchildren()[-1].tail += ' ' + second.text
except IndexError:
first.text += ' ' + second.text
root.append(first)
for child in second.getchildren():
root.append(child)
etree.tostring(root)

关于python - 使用 lxml 合并来自两个段落的 HTML 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44562565/

26 4 0
文章推荐: c++ - 根据模板参数调用不同版本的模板成员函数
文章推荐: javascript - 将变量传递到符合 W3C 的外部 js 文件中
文章推荐: c++ - 使用 istreambuf_iterator<> 将文件内容转换为字符串流
文章推荐: javascript - 单击按钮刷新
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com