1

我在 python 中有一个字符串和一个“规则”字典,或者可能对字符串进行更改。例如,一个规则可能有一个键'he'和一个值'e',或者一个键'll'和一个值'l'

这些规则意味着在我的字符串中任何出现的“他”都可以用一个替换'e',和类似'll''l'

我想要的是找到我的字符串的所有变体,给定这个规则字典。例如,使用上面的两个规则和 string 'hello',我想返回:

['hello', 'ello', 'helo', 'elo']

任何帮助表示赞赏,谢谢!

4

1 回答 1

4

编写一个接受输入的子字符串的递归函数。然后该函数检查所有规则。对于每个匹配的规则,都会进行一次替换,然后通过递归调用处理字符串的其余部分:

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']

请注意,我不允许将规则应用于替换的字符串,以防止出现无限结果的情况,如对此问题的评论所示。

于 2015-05-10T17:15:37.827 回答