2017-05-25 54 views
2

我试图创建一个包含字符替换的所有可能组合的单词列表,通过更改多个字符和它们各自的列表。输入也是一个关键字列表。例如:蟒蛇 - 带有列表的字符替换组合

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() 

回答

-1

首先,不要存放这种在不同的变量数据。这个数据要求这样一个字典:

options = { 
    'a': ['a', '4', '@'], 
    'y': ['y', 'ყ'], 
} 

这样你只需要修改一点功能。相反,具有单值进行核对身份,检查它是否在你的字典里:

[c,] if c not in options else options[c] 
+0

谢谢你,看到这些后我几分钟就能解决问题。我用我目前的解决方案编辑了这篇文章。 – jca12

0

可能有其他的方法,但既然你用一个开始时我将与继续。

def filler_list(word_list, from_char, to_char): 
    return_list=[] 
    for word in word_list: 
     return_list=return_list+list(filler(word,from_char,to_char)) 
    return return_list 

然后,只需在每一个字符循环即开始列表(填料(“魔”,“一个”,“4”)) 并通过它输出到filler_list作为输入和字符改变,因此在此会给你你的答案可能有一些重复,但他们可以删除,如果不是必要的,希望这有助于干杯!

0

迭代+递归。

考虑只有一个词,'魔术'。

依次看每个字母。魔法。 (重复)。它是否可以被替换的字母列表中?如果是这样,则进行替换并在结果列表中保留替换后的表格。现在,如果这是'魔术'中的最后一个字母,请继续迭代,否则开始递归下降,在该位置保留该字母的选择,但为下一个可替换字母提供所有可能的选择。

等完成。