【问题标题】:Find all combinations (upper and lower and symbols) of a word in python在python中查找单词的所有组合(大小写和符号)
【发布时间】:2012-06-25 01:29:09
【问题描述】:

我希望现在是星期一,但我觉得 应该 很容易 - 或者至少优雅 - 让我大吃一惊。用例是这样的:

查找特定单词的所有可能组合,其中字母可以不分大小写或替换为字母。例如:

单词:'密码' 组合:'PASSWORD'、'P@ssw0rd'、'p@55w0rD' ...

我不想写 7 个循环来找出这个问题,即使这是一个我们永远不会再使用的一次性脚本。

【问题讨论】:

标签: python iteration combinations


【解决方案1】:
import itertools

places = [
    "Pp",
    "Aa@",
    "Ss5",
    "Ss5",
    "Ww",
    "Oo0",
    "Rr",
    "Dd",
]

for letters in itertools.product(*places):
    print "".join(letters)

如果您需要处理任意单词,则需要编写代码从字符串创建places 列表。

【讨论】:

  • 我试过itertools.product,但没有意识到它可能需要几个迭代。我知道这很容易,谢谢。
【解决方案2】:

这个问题的主要问题是不是所有的字母都可以翻译成符号或数字。您必须创建一个字典,其中键是小写字母,值是该字母所有可能替换的列表:

{'a':['a','A','@'],...,'s':['s','S','5'],...,}

一旦你的字典建立起来,剩下的只是一个简单的笛卡尔积的问题,不同的列表以正确的顺序排列。

【讨论】:

    【解决方案3】:

    我会使用itertools.product:

    import itertools
    symbols = dict(a="@", s="5", o="0")  # char -> str
    text = "password"
    print list(itertools.product(*[[letter, letter.upper()] + list(symbols.get(letter, "")) for letter in text.lower()])
    

    【讨论】:

      【解决方案4】:

      itertools.product 是您要搜索的内容:

      #!/usr/bin/python
      # -*- coding: utf-8 -*-
      
      from itertools import product
      
      def getAllCombinations(password):
          leet = ["Aa@","Bb","Cc", "Dd","Ee","Ff","Gg","Hh","Ii","Jj","Kk",
                  "Ll","Mm","Nn","Oo0","Pp","Qq","Rr","Ss5","Tt","Uu","Vv",
                  "Ww","Xx","Yy","Zz"]
      
          getPlaces = lambda password: [leet[ord(el.upper()) - 65] for el in password]
      
          for letters in product(*getPlaces(password)):
              yield "".join(letters)
      
      for el in getAllCombinations("Password"):
          print el
      

      如果您对asterisk * 的含义感到好奇,请访问:foggy on asterisk in python

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-15
        • 2020-08-04
        • 2019-08-20
        • 1970-01-01
        • 1970-01-01
        • 2012-07-10
        • 2014-05-18
        • 2014-11-28
        相关资源
        最近更新 更多