python - 字符替换组合与列表

python - character replacement combinations with a list

我正在尝试创建一个单词列表,其中包含所有可能的字符替换组合,方法是将多个字符更改为各自的列表。输入也是关键字列表。示例:

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

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

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

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

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

可能还有其他方法,但既然你是从一个开始的,我会继续这样做。

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

然后循环遍历每个字符,即从 list(filler("magic", "a", "4")) 开始 并在输入和字符更改时将其输出传递给 filler_list 等等,这会给您答案,可能会重复一些,但如果不需要,可以将其删除,希望这有帮助干杯!

迭代+递归。

只考虑一个词,'magic'。

依次看每个字母。魔法。 (迭代)。它在可以替换的字母列表中吗?如果是这样,进行替换并在结果列表中保留替换的形式。现在,如果那是 'magic' 中的最后一个字母,则继续迭代,否则开始递归下降,将选择的字母保持在该位置,但考虑下一个可替换字母的所有可能选择。

以此类推完成。