[英]Find and replace a specific capturing group regex
我有以下形式的字符串列表:
ae nd <> 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 gz ae mp ax l <> ah v <> f ay n <> t ax p aa gr 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 <,>
其中第 4 个和第 6 个<>
已被替换为<> |
到目前为止,我已经用这个正则表达式捕获了所有组:
break_match = re.compile("[<]?.[>]+")
for match in re.finditer(break_match, sentence_match):
match_group = match.group(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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.