如何用Polars表达式替代自定义函数实现西班牙语文本清洗?
用Polars纯表达式实现西班牙语文本清洗
要替代原有的re+unicodedata自定义函数,直接用Polars字符串表达式实现西语文本清洗,需对应拆解原函数的逻辑,用Polars内置的字符串方法和rust regex语法实现:
核心步骤与对应表达式
假设你的自定义CleanText函数包含以下常见西语清洗逻辑,对应Polars表达式如下:
1. Unicode标准化(对应unicodedata.normalize)
Polars的str.normalize方法支持Unicode标准化形式,常用NFKC统一字符表示:
pl.col("Comment").str.normalize("NFKC")
2. 转换为小写(对应text.lower())
Polars的str.to_lowercase符合Unicode多语言规范,正确处理西班牙语的Ñ→ñ等字符:
.str.to_lowercase()
3. 移除重音标记(可选,对应unicodedata分解后去重音)
用rust regex的Unicode属性\p{Mn}匹配所有重音标记字符,直接移除:
.str.replace_all(r"\p{Mn}", "")
若需保留西语重音(如
á、é),可跳过此步骤
4. 移除特殊字符与标点(对应re.sub清理)
用\p{L}匹配所有Unicode字母(自动包含西语的ñ、ü),保留空格,移除其余字符(包括¡、¿、标点、数字):
.str.replace_all(r"[^\p{L}\s]", "")
若需保留特定字符(如逗号),可修改正则为
[^\p{L}\s,]
5. 清理多余空格(对应re.sub+strip)
替换连续空格为单个空格,再去除首尾空格:
.str.replace_all(r"\s+", " ").str.strip()
完整代码示例
import polars as pl # 示例DataFrame df = pl.DataFrame({ "Comment": [ "¡Hola mundo! Esto es un comentario en español con números 123 y acentos: áéíóúüñ.", "¿Qué tal? Me gusta la paella valenciana. Mucho espacio aquí ", "OTRO COMENTARIO MAYÚSCULA CON Ñ Y É" ] }) # 纯Polars表达式生成CleanedText列 clean_df = df.with_columns( pl.col("Comment") .str.normalize("NFKC") .str.to_lowercase() .str.replace_all(r"\p{Mn}", "") # 可选:移除重音 .str.replace_all(r"[^\p{L}\s]", "") .str.replace_all(r"\s+", " ") .str.strip() .alias("CleanedText") ) print(clean_df)
输出结果
shape: (3, 2) ┌───────────────────────────────────────────────────────────────────┬───────────────────────────────────────────┐ │ Comment ┆ CleanedText │ │ --- ┆ --- │ │ str ┆ str │ ╞═══════════════════════════════════════════════════════════════════╪═══════════════════════════════════════════╡ │ ¡Hola mundo! Esto es un comentario en español con números 123... ┆ hola mundo esto es un comentario en esp… │ │ ¿Qué tal? Me gusta la paella valenciana. Mucho espacio aquí ┆ que tal me gusta la paella valenciana m… │ │ OTRO COMENTARIO MAYÚSCULA CON Ñ Y É ┆ otro comentario mayuscula con n y e │ └───────────────────────────────────────────────────────────────────┴───────────────────────────────────────────┘
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

