语料库安全清洗技术咨询:精准实现脚注移除、空格规整与引号替换
解决语料库清洗的精准方案
针对你遇到的误修改问题,我们可以通过精准的正则匹配规则区分需要处理的脚注和要保留的内容(比如DC2),同时完成标点空格规整和引号替换。下面是分步实现的完整方案:
核心思路拆解
我们分三个模块处理,每个模块用针对性规则避免误操作:
- 精准移除指定脚注:
- 逗号后的数字脚注:仅匹配
,数字格式且数字后是空格/文本结尾的情况,避免误改类似,123abc的内容 - 星座名称后的数字脚注:先定义明确的星座列表,仅匹配这些特定单词后的数字
- 逗号后的数字脚注:仅匹配
- 规整标点空格:分两步处理——先移除标点前的多余空格,再统一标点后为单个空格
- 替换不规范引号:直接全局替换即可
完整实现代码
import re # 定义需要匹配的星座名称列表(包含12个完整星座名,可按需补充缩写) CONSTELLATIONS = r'(Aries|Taurus|Gemini|Cancer|Leo|Virgo|Libra|Scorpio|Sagittarius|Capricorn|Aquarius|Pisces)' def clean_corpus(text): # 1. 替换不规范引号为" text = re.sub('”', '"', text) # 2. 精准移除脚注 # 移除逗号后的数字脚注(确保数字后是空格或文本结尾) text = re.sub(r',\d+(?=\s|$)', '', text) # 移除星座名称后的数字脚注(仅匹配指定星座名后的数字) text = re.sub(fr'{CONSTELLATIONS}(\d+)', r'\1', text) # 3. 规整标点前后的空格 # 第一步:移除标点前的多余空格 text = re.sub(r'\s+([.!?:;,])', r'\1', text) # 第二步:确保标点后仅保留一个空格 text = re.sub(r'([.!?:;,])\s+', r'\1 ', text) # 去除文本首尾多余空格(可选) text = text.strip() return text
测试验证
测试示例文本
输入:
On 1580 November 12 at 10h 50m,1 they set Mars down at 8° 36’ 50” Gemini2 without mentioning the horizontal variations, by which term I wish the diurnal parallaxes and the refractions to be understood in what follows. Now this observation is distant and isolated. It was reduced to the moment of opposition using the diurnal motion from the Prutenic Tables .
输出:
On 1580 November 12 at 10h 50m they set Mars down at 8° 36’ 50" Gemini without mentioning the horizontal variations, by which term I wish the diurnal parallaxes and the refractions to be understood in what follows. Now this observation is distant and isolated. It was reduced to the moment of opposition using the diurnal motion from the Prutenic Tables.
测试边缘情况(避免误改)
输入:DC2 is a code, and Pisces3 is a constellation,4
输出:DC2 is a code, and Pisces is a constellation
可以看到DC2被完整保留,只有星座Pisces后的数字和逗号后的数字脚注被移除,完全符合需求。
关键规则说明
,\d+(?=\s|$):正向预查确保逗号后的数字后面是空格或文本结尾,避免误改带数字的复合内容fr'{CONSTELLATIONS}(\d+)':仅匹配指定星座名称后的数字,替换时保留星座名本身\s+([.!?:;,]):匹配一个或多个空格加标点,替换为标点本身,移除标点前的多余空格([.!?:;,])\s+:匹配标点加一个或多个空格,替换为标点加一个空格,统一标点后的空格数量
内容的提问来源于stack exchange,提问作者DevAM




