Skip to main content
 首页 » 编程设计

python之字符替换组合与列表

2025年05月04日7findumars

<分区>

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

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