python - 带有列表的字符替换组合[重复]

问题描述 投票:0回答:3

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

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()
python string combinations product python-itertools
3个回答
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

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


0
投票

迭代+递归。

只考虑“魔法”这个词。

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

以此类推。


-2
投票

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

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

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

[c,] if c not in options else options[c]
© www.soinside.com 2019 - 2024. All rights reserved.