gpt4 book ai didi

python - 在 BeautifulSoup 中用标签包装文本的小节

转载 作者:太空狗 更新时间:2023-10-29 14:55:41 25 4
gpt4 key购买 nike

我想要 BeautifulSoup 相当于 this jQuery question .

我想在 BeautifulSoup 文本中找到特定的正则表达式匹配项,然后用包装版本替换该文本段。我可以用纯文本包装来做到这一点:

# replace all words ending in "ug" wrapped in quotes,
# with "ug" replaced with "ook"

>>> soup = BeautifulSoup("Snug as a bug in a rug")
>>> soup
<html><body><p>Snug as a bug in a rug</p></body></html>
>>> for text in soup.findAll(text=True):
... if re.search(r'ug\b',text):
... text.replaceWith(re.sub(r'(\w*)ug\b',r'"\1ook"',text))
...
u'Snug as a bug in a rug'
>>> soup
<html><body><p>"Snook" as a "book" in a "rook"</p></body></html>

但是如果我想要粗体而不是引号怎么办?例如期望的结果 =

<html><body><p><b>Snook</b> as a <b>book</b> in a <b>rook</b></p></body></html>

最佳答案

for text in soup.findAll(text=True):
if re.search(r'ug\b',text):
text.replaceWith(BeautifulSoup(re.sub(r'(\w*)ug\b',r'<b>\1ook</b>',text),'html.parser'))

soup
Out[117]: <html><body><p><b>Snook</b> as a <b>book</b> in a <b>rook</b></p></body></html>

这里的想法是我们用完全形成的解析树替换标签。最简单的方法就是调用 BeautifulSoup在我们的正则表达式替换字符串上。

有点神奇的'html.parser'内部参数BeautifulSoup调用是为了防止它添加 <html><body><p>标签,就像 bs4(好吧,lxml 真的)通常那样。 More reading on that.

关于python - 在 BeautifulSoup 中用标签包装文本的小节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22700646/

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