使用正则表达式识别替换指定人名,排除已((PERS))封装内容
人名识别与替换需求
需要用Python正则表达式在目标字符串中识别并替换指定列表中的人名,需满足以下规则:
- 匹配条件:人名需处于空格之间、字符串首尾,或后接
[.,;](可无空格) - 排除条件:
- 已被
((PERS)name)结构封装的人名不再重复封装 - 排除人名作为单词一部分的场景(如
Edd's、pasteurization等)
- 已被
初始代码未实现上述逻辑,以下是修正后的完整代码:
import re # 待识别的人名列表 result_list = ['Thomas Edd', 'Melissa Clark', 'Ada White', 'Louis Pasteur', 'Edd Thomas', 'Clark Melissa', 'White Eda', 'Pasteur Louis', 'Thomas', 'Melissa', 'Ada', 'Louis', 'Edd', 'Clark', 'White', 'Pasteur'] # 按长度降序排序,优先匹配长人名,避免短人名截断长匹配 result_list.sort(key=len, reverse=True) # 测试输入文本 input_text = "((PERS)Melissa) went for a walk in the park, then Melisa Clark went to the cosmetics store. There Thomas showed her a wide variety of cosmetic products. Edd Thomas is a great salesman, even so ((PERS)Thomas Edd) is a skilled but responsible salesman, as Edd is always honest with his customers. White is a new client who came to Edd's business due to the good social media reviews she saw from Melissa, her co-worker." # 遍历人名列表执行替换 for name in result_list: # 构造正则表达式: # - (?<!\(\(PERS\)): 负向预查,排除已被((PERS))开头包裹的人名 # - \b: 单词边界,确保人名不是其他单词的一部分 # - re.escape(name): 转义人名中的特殊字符,避免正则语法错误 # - (?!\)): 负向预查,排除已被))结尾包裹的情况 # - (?=[\s.,;]|$): 正向预查,确保人名后符合匹配位置要求 pattern = rf'(?<!\(\(PERS\))\b{re.escape(name)}\b(?!\))(?=[\s.,;]|$)' input_text = re.sub(pattern, rf'((PERS){name})', input_text) print(repr(input_text))
预期输出
"((PERS)Melissa) went for a walk in the park, then ((PERS)Melisa Clark) went to the cosmetics store. There ((PERS)Thomas) showed her a wide variety of cosmetic products. ((PERS)Edd Thomas) is a great salesman, even so ((PERS)Thomas Edd) is a skilled but responsible salesman, as ((PERS)Edd) is always honest with his customers. ((PERS)White) is a new client who came to Edd's business due to the good social media reviews she saw from ((PERS)Melissa), her co-worker."
关键修正说明
- 排序逻辑:先按人名长度降序排序,确保长人名(如
Edd Thomas)优先匹配,避免短人名(如Edd)先匹配导致长人名被拆分 - 正则边界控制:通过
\b单词边界排除人名作为单词一部分的场景(如Edd's中的Edd不会被匹配) - 排除已封装的人名:使用负向预查
(?<!\(\(PERS\))和(?!\))确保已经被((PERS)name)包裹的人名不会被重复处理 - 匹配位置校验:通过
(?=[\s.,;]|$)确保人名处于符合要求的位置(空格、标点或字符串结尾)
内容的提问来源于stack exchange,提问作者Matt095
相关产品推荐
相关产品推荐

