我在python中有一个字符串和一个'rules'字典,或者对字符串的可能改动。例如,一条规则的密钥可能为'he'
,值为'e'
,密钥为'll'
且值为'l'
。
这些规则意味着我的字符串中出现的任何“他”都可以替换为'e'
,而'll'
和'l'
也是如此。
根据规则字典,我想要找到我的字符串的所有变体。例如,使用上面的两个规则和字符串'hello'
,我想返回:
['hello', 'ello', 'helo', 'elo']
感谢任何帮助,谢谢!
答案 0 :(得分: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']
请注意,我不允许对替换的字符串应用规则,以防止无效结果的情况,如本问题的评论中所示。