def match_and_replace(
text = None,
rule = None,
phoneme = None
):
"""
Replace found text from a single rule.
"""
# Find all rule matches.
matches = [(match.start(), match.end()) for \
match in re.finditer(rule, text)]
# Start from behind, so replace in-place.
matches.reverse()
# Convert to characters because strings are immutable.
characters = list(text)
for start, end in matches:
characters[start:end] = phoneme
# Convert back to string.
return "".join(characters)
评论列表
文章目录