> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 递归分割 - 文本分割器集成指南

> 这个 文本分割器 是通用文本推荐的分割器。它通过一组字符进行参数化。它会按顺序尝试在这些字符上分割文本，直到块足够小。默认列表是 ["\n\n", "\n", " ", ""]。这会尝试尽可能长时间地保持所有段落（然后是句子，然后是单词）作为一个整体，因为这些通常被认为是语义上最相关的文本片段。

这个 [文本分割器](https://langchain-docs-zh.mintlify.site/langchain/oss/integrations/splitters.md) 是通用文本推荐的分割器。它通过一组字符进行参数化。它会按顺序尝试在这些字符上分割文本，直到块足够小。默认列表是 `["\n\n", "\n", " ", ""]`。这会尝试尽可能长时间地保持所有段落（然后是句子，然后是单词）作为一个整体，因为这些通常被认为是语义上最相关的文本片段。

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

下面我们展示示例用法。

:::python

```shell theme={null}
pip install -qU langchain-text-splitters
```

:::
:::js

```bash npm theme={null}
npm install @langchain/textsplitters
```

```bash pnpm theme={null}
pnpm install @langchain/textsplitters
```

```bash yarn theme={null}
yarn add @langchain/textsplitters
```

```bash bun theme={null}
bun add @langchain/textsplitters
```

:::

:::python
要直接获取字符串内容，使用 `.split_text`。

要创建 LangChain @\[Document] 对象（例如，用于下游任务），使用 `.create_documents`。

```python theme={null}
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])
```

```python theme={null}
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.'
```

```python theme={null}
print(text_splitter.split_text(state_of_the_union)[:2])
```

```python theme={null}
['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.']
```

:::

:::js
要直接获取字符串内容，使用 `.splitText`。

要创建 LangChain @\[Document] 对象（例如，用于下游任务），使用 `.createDocuments`。

```ts theme={null}
import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";

const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 100, chunkOverlap: 0 })
const texts = splitter.createDocuments([{ pageContent: "..." }])
```

```javascript theme={null}
[
  { pageContent: "...", metadata: {} },
]
```

:::

让我们回顾上面为 `RecursiveCharacterTextSplitter` 设置的参数：

:::python

* `chunk_size`: 块的最大大小，其中大小由 `length_function` 决定。
* `chunk_overlap`: 块之间的目标重叠。重叠的块有助于在块之间分配上下文时减少信息丢失。
* `length_function`: 决定块大小的函数。
* `is_separator_regex`: 是否应将分隔符列表（默认为 `["\n\n", "\n", " ", ""]`）解释为正则表达式。
  :::

:::js

* `chunkSize`: 块的最大大小，其中大小由 `lengthFunction` 决定。
* `chunkOverlap`: 块之间的目标重叠。重叠的块有助于在块之间分配上下文时减少信息丢失。
  :::

## 从没有词边界的语言中分割文本

一些书写系统没有 [词边界](https://en.wikipedia.org/wiki/Category:Writing_systems_without_word_boundaries)，例如中文、日文和泰文。使用默认的分隔符列表 `["\n\n", "\n", " ", ""]` 分割文本可能会导致单词在块之间被分割。为了保持单词完整，您可以覆盖分隔符列表以包含额外的标点符号：

* 添加 ASCII 全角句号 "`.`"、[Unicode 全角](https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_\(Unicode_block\)) 全角句号 "`．`"（用于中文文本）以及 [表意全角](https://en.wikipedia.org/wiki/CJK_Symbols_and_Punctuation) "`。`"（用于日文和中文）
* 添加 [零宽空格](https://en.wikipedia.org/wiki/Zero-width_space)（用于泰文、缅甸文、高棉文和日文）
* 添加 ASCII 逗号 "`,`"、Unicode 全角逗号 "`，`" 和 Unicode 表意逗号 "`、`"

:::python

```python theme={null}
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
)
```

:::
:::js

```ts theme={null}
const splitter = new RecursiveCharacterTextSplitter({
  separators: [
    "\n\n",
    "\n",
    " ",
    ".",
    ",",
    "\u200b",  // Zero-width space
    "\uff0c",  // Fullwidth comma
    "\u3001",  // Ideographic comma
    "\uff0e",  // Fullwidth full stop
    "\u3002",  // Ideographic stop
    "",
  ],
});
```

:::

***

> 官方原文：[src/oss/integrations/splitters/recursive\_text\_splitter.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/integrations/splitters/recursive_text_splitter.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.