编写一个接受输入的子字符串的递归函数。然后该函数检查所有规则。对于每个匹配的规则,都会进行一次替换,然后通过递归调用处理字符串的其余部分:
def apply_rules(rules, input, start=0):
# First yield the outcome of no applied rules.
yield input[start:]
for match, replace in rules:
# Find the first match for this rule.
index = input.find(match, start)
if index < 0:
# No match -- skip to next one
continue
# Prepare the result of the replacement.
prefix = input[start:index] + replace
# Apply further rules to the rest of the string
# by a recursive call.
for suffix in apply_rules(rules, input, index + len(match)):
yield prefix + suffix
像这样使用它:
>>> rules = [('he','e'), ('ll','l'), ('e','ee')]
>>> list(apply_rules(rules, 'hello'))
['hello', 'ello', 'elo', 'helo', 'heello', 'heelo']
请注意,我不允许将规则应用于替换的字符串,以防止出现无限结果的情况,如对此问题的评论所示。