[英]How do you replace specific characters in beautifulSoup?
我很清楚如何使用bs4替换标签中的文本,但实际上我如何将p标签中的特定字符更改为b标签中包含的另一个字符或字符串?
例如,如果我想加粗/突出显示段落中的所有j。
如果要在文本中插入标签,则必须将整个文本分成三部分; 之前的所有内容,标记中的文本以及之后的所有内容。
每次在文本中找到匹配项时都必须执行此操作,因此在插入后也需要跟踪末段:
def inject_tag(text, start, end, tagname, **attrs):
# find the document root
root = text
while root.parent:
root = root.parent
before = root.new_string(text[:start])
new_tag = root.new_tag(tagname, **attrs)
new_tag.string = text[start:end]
after = root.new_string(text[end:])
text.replace_with(before)
before.insert_after(new_tag)
new_tag.insert_after(after)
return after
然后使用上面的函数替换特定的索引:
>>> import re
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''\
... <p>The quick brown fox jumps over the lazy dog</p>
... ''')
>>> the = re.compile(r'the', flags=re.I)
>>> text = soup.p.string
>>> while True:
... match = the.search(unicode(text))
... if not match: break
... start, stop = match.span()
... text = inject_tag(text, start, stop, 'b')
...
>>> print soup.prettify()
<html>
<head>
</head>
<body>
<p>
<b>
The
</b>
quick brown fox jumps over
<b>
the
</b>
lazy dog
</p>
</body>
</html>
您可以使用find_all()
函数以常规方式获取所有<p>
元素,以便为您想要的字母注入<b>
元素,例如:
from bs4 import BeautifulSoup
import sys
import re
soup = BeautifulSoup(open(sys.argv[1]))
for p in soup.find_all('p'):
p.string = re.sub(r'(r)', r'<b>\1</b>', p.string)
print(soup.prettify(formatter=None))
请注意,我使用formatter=None
来避免HTML实体的转换。
使用此测试文本:
<div>
<div class="post-text" itemprop="text">
<p>I'm well aware on how to replace texts in tags using bs4 but how would I actually change a specific character in, say a p-tag, into another character or string enclosed in a b-tag?</p>
<p>An example would be if I wanted to bold/highlight all the j's in a paragraph.</p>
</div>
</div>
像这样运行:
python script.py infile
产生:
<html>
<body>
<div>
<div class="post-text" itemprop="text">
<p>
I'm well awa<b>r</b>e on how to <b>r</b>eplace texts in tags using bs4 but how would I actually change a specific cha<b>r</b>acte<b>r</b> in, say a p-tag, into anothe<b>r</b> cha<b>r</b>acte<b>r</b> o<b>r</b> st<b>r</b>ing enclosed in a b-tag?
</p>
<p>
An example would be if I wanted to bold/highlight all the j's in a pa<b>r</b>ag<b>r</b>aph.
</p>
</div>
</div>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.