【问题标题】:Generate all possibilities for a string where some letters can be numbers, in Python在 Python 中为字符串生成所有可能的字符串,其中一些字母可以是数字
【发布时间】:2017-12-05 01:35:36
【问题描述】:

假设我有一个这样的字符串。

sentence = "i like to go fishing on saturday"

有些字母可以是数字,在“1337”的传统中,例如 h3110, h0w 4r3 y0u?

但是,我想获得所有可能的组合,其中一些字母被转换为数字,而另一些则不是。上面这句话的一些例子。

"i 1ik3 70 g0 fishing 0n s4turd4y"
"i lik3 70 g0 fishing 0n s4turd4y"
"i like 70 g0 fishing 0n s4turd4y"
"i 1ike 70 g0 fishing 0n s4turd4y"
etc.

如何在 Python 中为每个字母编写一个替换字典,然后为该句子生成所有可能的组合?

【问题讨论】:

  • 我有一种感觉,你会被这类问题存在的组合数量所震撼。大多数人...
  • 你的 python 字典在哪里显示字母到数字的替换?至少展示一下,也许我们可以在第二部分为您提供帮助。
  • @alfasin 我希望你喜欢我的讽刺评论,就像我喜欢你的光顾评论一样! @Shadow 对于我想使用的实际短语和我允许的替换,它是 1280 种组合。 @RoadRunner我不想提供我将如何实现替换,因为它可能会人为地限制某人的答案。例如,在 Paul Panzer 接受的答案中,我从未想过自己会这样做。但是,我的方式是这样的 {'a': ['4'], 'i': ['!', '1'], 'l': ['1'] }。保罗的要清楚得多。

标签: python combinations


【解决方案1】:

您可以从对构建字典,然后将itertools.product 用于所有组合:

import itertools

# 1: write down pairs
pairs = ['a4', 't7', 'e3'] # etc.
# 2: make dict; it will be convenient to store both letter and substitute as value
pd = {p[0]:p for p in pairs}
# 3: replace all eligible letters with the appropriate pair and
#    use itertools.product
[''.join(c) for c in itertools.product(*(pd.get(i, i) for i in 'i like to go fishing on saturday'))]
# ['i like to go fishing on saturday', 'i like to go fishing on saturd4y', 
#  'i like to go fishing on sa7urday', 'i like to go fishing on sa7urd4y',
#  'i like to go fishing on s4turday', 'i like to go fishing on s4turd4y',
#  'i like to go fishing on s47urday', 'i like to go fishing on s47urd4y',
#  'i like 7o go fishing on saturday', 'i like 7o go fishing on saturd4y',
#  'i like 7o go fishing on sa7urday', 'i like 7o go fishing on
#  ...

【讨论】:

  • 这是完美的,谢谢。不知道itertools中的product函数。
【解决方案2】:

写一个替换列表,比如

[
  [1, 'l'],
  [3, 'e'],
  [4, 'a'],
  ...
]

接下来,将您的文本分成几个部分,将您可以替换的任何字母分开。例如,“周六钓鱼”变成了

[ "fishing ", "o", "n s", "a", "turd", "a", "y"]

现在,为所有适当的字母引入替换列表:在这种情况下为o a a。使用itertools.product 生成所有可能的组合。

这足以让您入门吗?实施留给学生作为练习。

【讨论】:

    【解决方案3】:

    您可以创建字典手册。但是得到itertools.combinations的所有组合

    from itertools import combinations
    
    sentence = "i like to go fishing on saturday"
    
    d = {'l' : '1',
         'e' : '3',
         't' : '7'}
    
    for l in range(len(d)):
        for x in combinations(d, l):
            for k in x:
                s = sentence.replace(k, d[k])
                print(s)
    

    但是这个版本会将所有t 替换为7。不符合您的所有要求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      相关资源
      最近更新 更多