跳到主要内容
Open In ColabOpen on GitHub

如何按字符递归分割文本

这种文本分割器是通用文本推荐的。它由一个字符列表参数化。它会尝试按顺序使用这些字符进行分割,直到块足够小。默认列表是 ["\n\n", "\n", " ", ""]。这样做的好处是尽可能地保持所有段落(然后是句子,再然后是单词)的完整性,因为这些通常在语义上是关联最强的文本片段。

  1. 文本如何分割:通过字符列表。
  2. 块大小如何衡量:按字符数。

下面展示示例用法。

要直接获取字符串内容,请使用 .split_text

要创建朗链 Document 对象(例如,用于下游任务),请使用 .create_documents

%pip install -qU langchain-text-splitters
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])
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.'
text_splitter.split_text(state_of_the_union)[: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 句号 "."、Unicode 全角句号 ""(中文文本中使用)和表意文字句号 ""(日文和中文中使用)。
  • 添加在泰语、缅甸语、高棉语和日语中使用的零宽度空格
  • 添加 ASCII 逗号 ","、Unicode 全角逗号 "" 和 Unicode 表意文字逗号 ""
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
)