Skip to main content
Open In Colab在 GitHub 上打开

如何按字符递归拆分文本

文本拆分器是推荐用于通用文本的拆分器。它由字符列表参数化。它尝试按顺序对它们进行拆分,直到块足够小。默认列表为["\n\n", "\n", " ", ""].这样做的效果是尝试将所有段落(然后是句子,然后是单词)尽可能长时间地放在一起,因为这些通常看起来是语义上最强的文本片段。

  1. 文本的拆分方式:按字符列表。
  2. 如何测量块大小:按字符数。

下面我们显示了示例用法。

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

要创建 LangChain 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", " ", ""]) 应解释为 regex。

从没有单词边界的语言中拆分文本

某些书写系统没有单词边界,例如中文、日语和泰语。使用默认分隔符列表["\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
)