Ich möchte die BeautifulSoup Entsprechung von this jQuery question.Wrapping Unterabschnitte von Text mit Tags in BeautifulSoup
Ich möchte eine bestimmte Regex-Übereinstimmung in BeautifulSoup Text finden und ersetzen Sie dann dieses Segment des Textes mit einer verpackten Version. Ich kann dies mit Klartextumhüllung tun:
# 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>
Aber was, wenn ich Fettdruck anstatt Anführungszeichen möchte? z.B. gewünschtes Ergebnis =
<html><body><p><b>Snook</b> as a <b>book</b> in a <b>rook</b></p></body></html>