我正在嘗試編寫函數,它將根據預定義的字典為我提供給定字符串的所有可能組合。假設示例:dict = {'a':'á', 'a':'?', 'y':'y'}string = "antony"word_combination(string, dict) #desired function預期結果應該是:["antony", "ántony", "?ntony", "ántony", "?ntony", "antony"]即我們創建了定義字符串的所有可能組合,并根據定義的字典進行替換。請問有什么建議/技巧嗎?
1 回答

狐的傳說
TA貢獻1804條經驗 獲得超3個贊
這是將字典轉換為有效字典后的解決方案:
import itertools
d = {'a':['á','?'], 'y':['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)
結果是:
['ánthony', 'ánthony', '?nthony', '?nthony', 'anthony', 'anthony']
添加回答
舉報
0/150
提交
取消