LangChain:基于文本结构的的文本切割器

文本自然地被组织为段落、句子和单词等层级单元。我们可以利用这种固有结构来指导分割策略,从而创建既能保持自然语言流畅性、又能维持分块内语义连贯性、还能适应不同文本粒度的分块。

LangChain 的递归字符文本分割器(RecursiveCharacterTextSplitter)实现了这一理念。

基于文本结构的切割

递归文本切割

递归文本切割器RecursiveCharacterTextSplitter

  • 该分割器会优先尝试保持较大单元(如段落)的完整性。
  • 若某单元超出分块大小,则降级至下一层级(如句子)进行分割。
  • 如有必要,此过程将持续进行,直至细化到单词级别。

使用示例

1
2
3
4
from langchain_text_splitters import RecursiveCharacterTextSplitter

text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=0)
texts = text_splitter.split_text(document)

Recursively split text

Recursively split text:递归切割文本

该文本分割器(text splitter)是处理常规文本的推荐工具。它通过一个字符列表进行参数化,并按列表中字符的顺序尝试分割,直至分块达到合适的大小。

默认字符列表为 ["\n\n", "\n", " ", ""]。这种设计旨在尽可能保持段落(然后是句子,最后是单词)的完整性,因为这些通常是语义关联性最强的文本单元。

  • 文本分割方式:依据字符列表进行分割。
  • 分块大小计量方式:按字符数量计算。

使用示例

安装依赖

1
pip install -qU langchain-text-splitters

要直接获取文本内容,使用 .split_text

要创建 LangChain Document 的文本对象(例如,要给下游任务使用),使用.create_documents

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from langchain_text_splitters import RecursiveCharacterTextSplitter

# Load example document
with open("state_of_the_union.txt") as f:
state_of_the_union = f.read()

text_splitter = RecursiveCharacterTextSplitter(
# Set a really small chunk size, just to show.
chunk_size=100,
chunk_overlap=20,
length_function=len,
is_separator_regex=False,
)
texts = text_splitter.create_documents([state_of_the_union])
print(texts[0])
print(texts[1])
1
2
page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and'
page_content='of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.'
1
print(text_splitter.split_text(state_of_the_union)[:2])
1
2
['Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and',
'of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.']

看一下上述为 RecursiveCharacterTextSplitter 设置的参数:

  • chunk_size:块的最大大小,其值由 length_function 决定。
  • chunk_overlap:块之间的目标重叠长度。块之间的重叠有助于减少因上下文被分割到不同块而导致的信息丢失。
  • length_function:决定块大小的函数。
  • is_separator_regex:指定分隔符列表(默认是 ["\n\n", "\n", " ", ""])应被解释为正则表达式。

分割无单词边界语言的文本

某些书写系统没有单词边界,例如中文、日文和泰文。使用默认分隔符列表 ["\n\n", "\n", " ", ""] 进行文本分割可能会导致单词被分割到不同的块中。为保持单词完整性,可以通过覆盖分隔符列表来添加额外的标点符号:

  • 添加 ASCII 句号 “.”、中文使用的全角句点 “。” 以及中日文使用的表意句号 “。”
  • 添加泰文、缅文、高棉文和日文中使用的零宽空格
  • 添加 ASCII 逗号 “,”、全角逗号 “,” 以及表意逗号 “、”
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
text_splitter = RecursiveCharacterTextSplitter(
separators=[
"\n\n",
"\n",
" ",
".",
",",
"\u200b", # Zero-width space
"\uff0c", # Fullwidth comma
"\u3001", # Ideographic comma
"\uff0e", # Fullwidth full stop
"\u3002", # Ideographic full stop
"",
],
# Existing args
)
作者

光星

发布于

2026-02-24

更新于

2026-02-25

许可协议

评论