2

我目前正在开展一个项目,我希望在该项目中允许在大量 HTML 文件中/上进行正则表达式搜索。

在首先确定我感兴趣的文件之后,我现在想突出显示找到的关键字!

使用 BeautifulSoup,我可以确定找到我的关键字的节点。我做的一件事是改变整个父母的颜色。

但是,我还想在我找到的关键字周围添加我自己的 <span>-Tags。

使用 BFSoup 提供的 find() 函数确定位置等没什么大不了的。但是在常规文本周围添加我的标签似乎是不可能的?

# match = keyword found by another regex
# node = the node I found using the soup.find(text=myRE)
node.parent.setString(node.replace(match, "<myspan>"+match+"</myspan>"))

这样我只添加了文本而不是适当的标签,因为文档不是新解析的,我希望避免这种情况!

我希望我的问题变得有点清楚:)

4

2 回答 2

3

这是一个简单的示例,显示了一种方法:

import re
from bs4 import BeautifulSoup as Soup

html = '''
<html><body><p>This is a paragraph</p></body></html>
'''

(1) 存储文本并清空标签

soup = Soup(html)
text = soup.p.string
soup.p.clear()
print soup

(2)获取要加粗的单词的开始和结束位置(为我的英语道歉)

match = re.search(r'\ba\b', text)
start, end = match.start(), match.end()

(3) 拆分文本并添加第一部分

soup.p.append(text[:start])
print soup

(4) 创建一个标签,将相关文本添加到它并附加到父级

b = soup.new_tag('b')
b.append(text[start:end])
soup.p.append(b)
print soup

(5) 附加文本的其余部分

soup.p.append(text[end:])
print soup

这是上面的输出:

<html><body><p></p></body></html>
<html><body><p>This is </p></body></html>
<html><body><p>This is <b>a</b></p></body></html>
<html><body><p>This is <b>a</b> paragraph</p></body></html>
于 2013-02-01T23:47:54.397 回答
2

如果添加文字...

my_tag = node.parent.setString(node.replace(match, "<myspan>"+match+"</myspan>"))

...并再次通过 BeautifulSoup

new_soup = BeautifulSoup(my_tag)

它应该被归类为 BS 标记对象并且可用于解析。

您可以将这些更改应用于原始大量文本并将其作为一个整体运行,以避免重复。

编辑:

文档

# Here is a more complex example that replaces one tag with another: 

from BeautifulSoup import BeautifulSoup, Tag
soup = BeautifulSoup("<b>Argh!<a>Foo</a></b><i>Blah!</i>")
tag = Tag(soup, "newTag", [("id", 1)])
tag.insert(0, "Hooray!")
soup.a.replaceWith(tag)
print soup
# <b>Argh!<newTag id="1">Hooray!</newTag></b><i>Blah!</i>
于 2013-02-01T18:42:47.040 回答