Skip to main content
文本分割器是通用文本的推荐选择。它由一个字符列表参数化。它会按顺序尝试在这些字符上进行分割,直到块足够小。默认列表是 ["\n\n", "\n", " ", ""]。这具有尝试尽可能长时间地将所有段落(然后是句子,然后是单词)保持在一起的效果,因为这些通常似乎是语义上关联性最强的文本片段。
  1. 文本如何分割:按字符列表。
  2. 块大小如何测量:按字符数。
下面我们展示使用示例。
pip install -qU langchain-text-splitters
要直接获取字符串内容,请使用 .split_text 要创建 LangChain Document 对象(例如,用于下游任务),请使用 .create_documents
from langchain_text_splitters import RecursiveCharacterTextSplitter

# 加载示例文档
with open("state_of_the_union.txt") as f:
    state_of_the_union = f.read()

text_splitter = RecursiveCharacterTextSplitter(
    # 设置一个非常小的块大小,仅用于演示。
    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.'
print(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",  # 零宽空格
        "\uff0c",  # 全角逗号
        "\u3001",  # 表意文字逗号
        "\uff0e",  # 全角句点
        "\u3002",  # 表意文字句点
        "",
    ],
    # 现有参数
)