特定字符替换
更新时间:2026-05-18
特定字符替换
简介
特定字符替换算子,基于正则表达式对文本进行批量字符串替换,支持多组 pattern/replacement 规则。
功能描述
- 支持多个正则表达式模式的顺序替换
- 支持 Python regex 语法(包括 Unicode 属性等扩展语法)
- patterns 和 replacements 一一对应;replacements 为单值时对所有 pattern 使用同一替换字符串
- 空文本或 None 返回 None
算子参数
输入
| 输入 | 含义 |
|---|---|
| texts | 文本字符串数组 |
输出
| 输出 | 含义 |
|---|---|
| replaced_text | 替换后的文本(large_string),失败时返回 None |
参数
| 参数名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| patterns | list[str] | (必填) | 正则表达式模式列表,支持 Python regex 语法 |
| replacements | list[str] | (必填) | 替换字符串列表,与 patterns 一一对应;若只有 1 个则对所有 pattern 使用相同替换 |
调用示例
Plain Text
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.regex_replacement import RegexReplacer
10
11if __name__ == "__main__":
12 if os.getenv("DAFT_RUNNER", "native") == "ray":
13 import ray
14 ray.init(dashboard_host="0.0.0.0", ignore_reinit_error=True)
15 daft.set_runner_ray()
16 daft.set_execution_config(actor_udf_ready_timeout=6000, min_cpu_per_task=0)
17
18 samples = {"text": ["Hello World!!!", "特殊字符:@#$%^&*()", "Normal text."]}
19 ds = daft.from_pydict(samples)
20 constructor_kwargs = {
21 # 将多个空格替换为单个空格,将非字母数字中文字符替换为空
22 "patterns": [r"\s+", r"[^\w\u4e00-\u9fff\s]"],
23 "replacements": [" ", ""],
24 }
25 ds = ds.with_column(
26 "replaced_text",
27 aihc_udf(
28 RegexReplacer,
29 construct_args=constructor_kwargs,
30 num_cpus=1,
31 concurrency=4,
32 batch_size=1024,
33 )(col("text")),
34 )
35 ds.show()
评价此篇文章
