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

狐的傳說
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個贊
這是將字典轉(zhuǎn)換為有效字典后的解決方案:
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)
結(jié)果是:
['ánthony', 'ánthony', '?nthony', '?nthony', 'anthony', 'anthony']
添加回答
舉報
0/150
提交
取消