查找并替换特定的捕获组正则表达式

2024-06-25 23:27:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下格式的字符串列表:

ae n d <> ih t <> ih z <> w er th <> m eh n sh ax n <> ih n <> p ae s ih ng <> dh ae t <,> ae z <> ae n <> ih g z ae m p ax l <> ah v <> f ay n <> t ax p aa g r ax f iy <,>

这句话的意思是“值得顺便提一下,作为精细排版的一个例子”

我还有另一套表格文件:

4
6 

这意味着我需要将上面的字符串替换为

ae n d <> ih t <> ih z <> w er th <> | m eh n sh ax n <> ih n <> p ae s ih ng <> dh ae t <,> ae z <> ae n <> | ih g z ae m p ax l <> ah v <> f ay n <> t ax p aa g r ax f iy <,> 

其中第四和第六个<>已替换为<> |

到目前为止,我已经用这个正则表达式捕获了所有组:

break_match = re.compile("[<]?.[>]+")
for match in re.finditer(break_match, sentence_match):
    match_group = match.group(0)

但我不确定如何迭代捕获的组(因为它一次完成),然后替换它们


Tags: 字符串matchshaxngaadher
1条回答
网友
1楼 · 发布于 2024-06-25 23:27:21

你在找re.subrepl参数可以是一个函数,每个非重叠匹配都会调用该函数(将匹配对象作为其一个参数,并返回要替换的字符串)。因此,您可以使用一个类来跟踪状态,并根据需要传入一个成员函数来执行(或不执行)替换

一个快速而肮脏的示例可能如下所示:

class WordCount(object):
    def __init__(self, counts):
        self.counts = counts
        self.cur_count = counts.pop(0) if counts else None

    def replace_word_break(self, match):
        if self.cur_count is None:
            # we're done; don't replace anything else
            return match.group(0)
        self.cur_count -= 1
        if self.cur_count:
            # haven't reached the next break; don't replace
            return match.group(0)
        # we've reached a break; figure out next count and replace
        self.cur_count = self.counts.pop(0) if self.counts else None
        return "{} |".format(match.group(0))

word_counter = WordCount([4, 6])
result = break_match.sub(word_counter.replace_word_break, sentence_match)

相关问题 更多 >