我试图创建一个包含字符替换的所有可能组合的单词列表,通过更改多个字符和它们各自的列表。输入也是一个关键字列表。例如:蟒蛇 - 带有列表的字符替换组合
keywords=["magic", "mate"]
aoptions = ["a", "4", "@"]
boptions = ["b", "8"]
eoptions = ["e", "3"]
goptions = ["g", "9"]
ioptions = ["i", "1"]
loptions = ["l", "1"]
ooptions = ["o", "0"]
soptions = ["s", "5", "$"]
toptions = ["t", "7"]
zoptions = ["z", "2"]
期望的结果会是这样一个列表:
['magic', 'mag1c', 'ma9ic', 'ma91c'...'[email protected]', '[email protected]']
我只能够建立在一个时刻一个关键字的解决方案,并与另一个单取代单个字符字符。算法在这里找到String Replacement Combinations。它看起来像这样
from itertools import product
def filler(word, from_char, to_char):
options = [(c,) if c != from_char else (from_char, to_char) for c in word]
return (''.join(o) for o in product(*options))
导致:
>>> filler("magic", "a", "4")
<generator object <genexpr> at 0x8fa798c>
>>> list(filler("magic", "a", "4"))
['magic', 'm4gic']
这是不是特别重要,但关键字列表将从.txt文件每行一个关键字进行读取和结果的组合列表将被写入到每行一个单词的.txt文件中。我一直在尝试创建不同的迭代循环,并在没有任何运气的情况下修改itertools.product示例几天。任何和所有的帮助,非常感谢。
UPDATE: 更新基于#zefciu建议我的填充功能,我能够用这个方法来解决:
所有的from itertools import product
def filler(word):
combos = [(c,) if c not in options else options[c] for c in word]
return (''.join(o) for o in product(*combos))
options = {
'A': ['A', '4', '@'],
'B': ['B', '8',],
'E': ["E", "3"],
'G': ["G", "9"],
'I': ["I", "1", "!"],
'L': ["L", "1"],
'O': ["O", "0"],
'S': ["S", "5", "$"],
'T': ["T", "7"],
'Z': ["Z", "2"]}
with open('CustomList.txt', 'r') as f:
startlist = f.readlines()
startlist = [x.strip() for x in startlist]
startlist = [element.upper() for element in startlist]
filid= open('WordList.txt', 'w+')
for word in startlist:
temp_list=list(filler(word))
for newword in temp_list:
print >> filid, newword
filid.close()
谢谢你,看到这些后我几分钟就能解决问题。我用我目前的解决方案编辑了这篇文章。 – jca12