字符串变化



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

这些规则意味着我的字符串中的任何`'他'的发生都可以用 'e'替换,而对于'll''l'

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

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

任何帮助将不胜感激,谢谢!

编写递归功能,该函数采用输入的子字符串。然后,此功能检查所有规则。对于匹配的每个规则,都可以完成一个替换,其余的字符串由递归调用处理:

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

请注意,我不允许在替换字符串上应用规则,以防止该问题评论中所示的无限结果案例。

相关内容

最新更新