如何用Python正则捕获符合起止规则的子串并重构字符串
地点副词子串的正则捕获与重构
需求说明
需要处理输入字符串,完成以下操作:
- 将所有以
list_all_adverbs_of_place列表内的地点副词开头的子串,封装为((PL_ADVB)文本)格式(开头的地点副词需包含在内) - 捕获终止条件满足以下任一即可:
- 遇到
((NOUN)任意文本)模式 - 遇到
list_limiting_elements列表中的任意元素 - 捕获文本内出现第二个地点副词时,以该副词作为结束边界
- 遇到
- 通过
re.sub()实现字符串重构,忽略大小写匹配
解决方案代码
import re # 输入字符串 capture_where_capsule = "alrededor ((NOUN)del auto rojizo, algo grande y completamente veloz). Luego dentro del baúl rápidamente abajo de una caja por sobre ello vimos una caña." # 地点副词列表(触发捕获的起始词) list_all_adverbs_of_place = ["adentro", "dentro", "al rededor", "alrededor", "abajo", "hacía", "hacia", "por sobre", "sobre"] # NOUN模式 descriptive_noun_pattern = r"\(\(NOUN\)[\w,;.\s]+\)" # 各类限制元素列表 list_verbs = ["vimos", "hemos visto", "encontramos", "hemos encontrado"] list_adverbs_of_manner = ["rápidamente", "rapidamente", "intensamente", "gradualmente", "completamente"] list_adverbs_of_time = ["durante", "luego", "ahora", "mientras tanto"] list_limitant_words = ["a las", "a los", "a la", "a el", "a los", "a las", "a mí", "a mi", "a sus", "a su", "a él", "a ella", "talvez", "tal vez", "tal", "al", "los", "las", "él", "el", "la", "cómo", "como" , "con", "en su", "en mi", "en", ".", ":", ";", ",", "(", ")", "[", "]", "¿", "?", "¡", "!", "&", "="] # 合并所有终止触发元素 list_limiting_elements = list_verbs + list_adverbs_of_manner + list_adverbs_of_time + list_limitant_words # 对地点副词按长度降序排序,确保多词副词优先匹配(比如先匹配"por sobre"而非"sobre") sorted_adverbs = sorted(list_all_adverbs_of_place, key=lambda x: -len(x)) # 转义副词中的特殊字符,构建匹配起始部分的正则 adv_pattern = re.compile(r'|'.join(re.escape(adv) for adv in sorted_adverbs), re.IGNORECASE) # 构建终止条件的正则:正向预查,匹配三种终止情况 # 1. 另一个地点副词 2. NOUN模式 3. 限制元素(转义特殊字符) escaped_limiting = [re.escape(item) for item in list_limiting_elements] termination_pattern = r'(?=(?:{}|{}|{}))'.format( adv_pattern.pattern, descriptive_noun_pattern, '|'.join(escaped_limiting) ) # 完整匹配模式:地点副词开头,匹配任意字符直到终止条件(非贪婪模式) full_pattern = re.compile(r'({})(.*?)(?=\s+{}|$)'.format(adv_pattern.pattern, termination_pattern), re.IGNORECASE | re.DOTALL) # 执行替换,将匹配到的内容封装为((PL_ADVB)...)格式 result = full_pattern.sub(r'((PL_ADVB)\g<0>)', capture_where_capsule) # 输出结果 print(repr(result))
输出结果
"((PL_ADVB)alrededor ((NOUN)del auto rojizo, algo grande y completamente veloz)). Luego ((PL_ADVB)dentro del baúl) rápidamente ((PL_ADVB)abajo de una caja) ((PL_ADVB)por sobre ello) vimos una caña."
内容的提问来源于stack exchange,提问作者Matt095
相关产品推荐
相关产品推荐

