python - 带有列表的字符替换组合

时间:2017-05-25 13:25:34

标签: python string combinations product itertools

我尝试通过使用各自的列表更改多个字符来创建包含所有可能的字符替换组合的单词列表。输入也是关键字列表。例如:

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'...'m@t3', 'm@73']

我只能一次创建一个关键字的解决方案,并用另一个单个字符替换单个字符。该算法在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示例几天没有运气。非常感谢任何和所有帮助。

更新 基于#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()

3 个答案:

答案 0 :(得分: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

然后循环遍历每个字符,即从列表开始(填充(&#34;魔术&#34;,&#34; a&#34;,&#34; 4&#34;)) 并将它的输出传递给filler_list作为输入和字符改变等等,这将给你答案可能有一些重复,但如果没有必要可以删除,希望这有助于干杯!

答案 1 :(得分:0)

迭代+递归。

只考虑一个词,&#39;魔术&#39;。

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

等等完成。

答案 2 :(得分:-1)

首先,不要将这种数据存储在单独的变量中。这个数据要求这样的字典:

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

这样你只需稍微修改一下这个功能。而不是使用单个值检查身份,检查它是否在您的字典中:

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