【问题标题】:Generation of the different string combination based on predefined string and dictionary基于预定义字符串和字典生成不同的字符串组合
【发布时间】:2020-07-10 14:56:23
【问题描述】:

我正在尝试编写函数,该函数将为我提供基于预定义字典的给定字符串的所有可能组合。假设示例:

dict = {'a':'á', 'a':'ä', 'y':'ý'}
string = "antony"
word_combination(string, dict) #desired function

预期结果应该是:

["antony", "ántony", "äntony", "ántoný", "äntoný", "antoný"]

即我们根据定义的 dictionary 创建了定义的 string 的所有可能组合进行替换。 请问有什么建议/提示吗?

【问题讨论】:

  • 你的字典无效,字典不能有重复的键。

标签: python string dictionary combinations


【解决方案1】:

将您的字典转换为有效字典后的解决方案如下:

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

【讨论】:

  • 非常感谢!只是为了完整性:在正确的解决方案行中,“用于替换梳中:”和“s = string”应该交换。
  • 糟糕。我的错。谢谢。更新了解决方案。
猜你喜欢
  • 2011-12-02
  • 2021-04-30
  • 2020-07-30
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 2012-11-18
相关资源
最近更新 更多