在Python中为字符串生成所有可能性,其中一些字母可以是数字

时间:2017-12-05 01:35:36

标签: python combinations

说我有这样的字符串。

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中写下每个字母的替换词典,然后为句子生成所有可能的组合?

3 个答案:

答案 0 :(得分:2)

您可以从对中构建字典,然后对所有组合使用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
#  ...

答案 1 :(得分:1)

写一个替换列表,例如

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

接下来,将文本划分为多个部分,分隔您可以替换的任何字母。例如,“星期六钓鱼”成为

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

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

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

答案 2 :(得分:1)

您可以创建字典手册。但是要获得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替换为// import { Appsee } from '@ionic-native/appsee'; declare var cordova:any; @Component({ templateUrl: 'app.html' }) export class MyApp { rootPage:any = LoginPage; // FOR TESTING constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) { platform.ready().then(() => { cordova.plugins.Appsee.start("my key"); // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. statusBar.styleDefault(); splashScreen.hide(); }); } } 。不符合您的所有要求。