文本分块
更新时间:2026-07-29
简介
TextChunk 按最大长度或分隔模式将文本切分为多个块,纯 regex(按字符长度)实现,可选 HuggingFace tokenizer(按 token 长度)。
功能描述
• 仅给 split_pattern:按 pattern 切分并过滤空段;仅给 max_len:按长度切分,块间可 overlap_len 重叠。
• 两者都给时递归切分:超过 max_len 时在 pattern 处强制切断。
• 可选传入 tokenizer 名称,则按 token 数而非字符数计长,切分后再解码回文本。
算子参数
输入
| 输入 | 含义 |
|---|---|
| text | 待切分的文本字符串 |
输出
| 输出 | 含义 |
|---|---|
| result | 类型 list<large_string>,即该条文本切出的块列表;输入为 None 时返回 None,出错时返回 [原文] |
参数
| 参数名称 | 类型 | 默认值 | 描述 | |
|---|---|---|---|---|
| max_len | int |None | None | 每块最大长度(tokenizer 为空时按字符数,否则按 token 数);与 split_pattern 不能同时为 None |
|
| split_pattern | str |None | r"\n\n" | 分隔正则模式;与 max_len 不能同时为 None |
|
| overlap_len | int | 0 | 块间重叠长度,必须小于 max_len |
|
| tokenizer | str |None | None | 可选 HuggingFace tokenizer 名称/路径;提供后按 token 计长,惰性加载 | |
| trust_remote_code | bool | False | 加载 tokenizer 时是否信任远程代码 |
调用示例
Python
1from __future__ import annotations
2
3import os
4
5import daft
6from daft import col
7
8from daft.aihc.common.udf import aihc_udf
9from daft.aihc.functions.text.text_chunk import TextChunk
10
11if __name__ == "__main__":
12 if os.getenv("DAFT_RUNNER", "native") == "ray":
13 import ray
14
15 ray.init(ignore_reinit_error=True)
16 daft.set_runner_ray()
17 daft.set_execution_config(actor_udf_ready_timeout=6000, min_cpu_per_task=0)
18
19 samples = {
20 "text": [
21 "First paragraph.\n\nSecond paragraph.\n\nThird paragraph.",
22 "Single block without separator.",
23 ]
24 }
25 ds = daft.from_pydict(samples)
26 ds = ds.with_column(
27 "chunks",
28 aihc_udf(
29 TextChunk,
30 construct_args={"split_pattern": r"\n\n", "max_len": None},
31 num_cpus=1,
32 concurrency=1,
33 batch_size=2,
34 )(col("text")),
35 )
36 ds.show()
评价此篇文章
