我正在尝试编写函数,它将根据预定义的字典为我提供给定字符串的所有可能组合。假设示例:dict = {'a':'á', 'a':'ä', 'y':'ý'}string = "antony"word_combination(string, dict) #desired function预期结果应该是:["antony", "ántony", "äntony", "ántoný", "äntoný", "antoný"]即我们创建了定义字符串的所有可能组合,并根据定义的字典进行替换。请问有什么建议/技巧吗?
1 回答
狐的传说
TA贡献1804条经验 获得超3个赞
这是将字典转换为有效字典后的解决方案:
import itertools
d = {'a':['á','ä'], 'y':['ý']}
string = "Anthony"
# if since each char can be replaced with itself, add it to the list of
# potential replacements.
for k in d.keys():
if k not in d[k]:
d[k].append(k)
res = []
for comb in [zip(d.keys(), c) for c in itertools.product(*d.values())]:
s = string
for replacements in comb:
s = s.replace(*replacements)
res.append(s)
结果是:
['ánthoný', 'ánthony', 'änthoný', 'änthony', 'anthoný', 'anthony']
添加回答
举报
0/150
提交
取消