字符串变化 [英] String Variations
问题描述
我在python中有一个字符串和规则"的字典,或者对该字符串的可能更改.例如,一个规则可能具有'he'
的键和'e'
的值,或者具有'll'
的键和'l'
的值.
I have a string in python and a dictionary of 'rules', or possible alterations to the string. For example, one rule might have a key of 'he'
and a value of 'e'
, or a key of 'll'
and a value of 'l'
.
这些规则意味着在我的字符串中出现的任何''he'都可以用'e'
替换,对于'll'
和'l'
类似.
These rules would mean that any occurrence of ``'he' in my string can be replaced with an 'e'
, and similarly for 'll'
and 'l'
.
给定这个规则字典,我想要的是找到我的字符串的所有变体.例如,使用上面的两个规则和字符串'hello'
,我想返回:
What I want is to find all variations of my string, given this dictionary of rules. For instance, with the two rules from above and the string 'hello'
, I would like to return:
['hello', 'ello', 'helo', 'elo']
感谢您的帮助,谢谢!
推荐答案
编写一个采用输入子字符串的递归函数.然后,此功能将检查所有规则.对于每个匹配的规则,将进行一次替换,并通过递归调用处理字符串的其余部分:
Write a recursive function that takes a substring of the input. This function then examines all rules. For each rule that matches, one replacement is done, and the remainder of the string is processed by a recursive call:
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']
请注意,我不允许在替换后的字符串上应用规则,以防止出现无限结果的情况,如对该问题的评论中所示.
Please note that I don't allow rules to be applied on replaced strings, to prevent cases of infinite results as demonstrated in the comments to this question.
这篇关于字符串变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!