Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找并替换特定的捕获组正则表达式_Python_Regex - Fatal编程技术网

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

Python 查找并替换特定的捕获组正则表达式,python,regex,Python,Regex,我有以下格式的字符串列表: 4 6 ae n d ih h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h g z a e h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h 这句

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

4
6 
ae n d ih h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h g z a e h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h

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

我还有另一套表格文件:

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 <,> 
a e n d ih h h h n sh ax n ih n p ae s h h h e e e z a e n h g z a e m p ax l v ay n t ax p a g r ax f iy
其中第四个和第六个
已替换为
|

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

break_match = re.compile("[<]?.[>]+")
for match in re.finditer(break_match, sentence_match):
    match_group = match.group(0)
break\u match=re.compile([]+”)
对于re.finditer中的匹配(断开匹配,句子匹配):
匹配组=匹配组(0)

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

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

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

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)