Python暴力通配符

2024-07-03 06:20:19 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我想写一封简单的信,用蛮力来表达五旬斋:

    astric = ['a', 'b', 'c', 'd', 'e', 'f', 'g','h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    usern = input("username you want to check with '*' for unknown chars: ")
    paramsGet = {"Name": usern}

因此,输入将询问用户名,我将输入meep**,然后将astric列表随机字母或数字分配给该列表,因此这将是一个完整的请求。我该怎么办? for _ in list: 我想大概是这样吧


Tags: toyou列表forinputcheckwithusername
3条回答

您可以尝试使用递归方法解决此问题

def getWords(words):
    matched_words = []
    break_flag = True
    for word in words:
        if '*' not in word:
            matched_words.append(word)
        else:
            break_flag = False
            for char in astric:
                matched_words.append(word.replace('*', char, 1))
    if break_flag:
        return matched_words
    else:
        return getWords(matched_words)
print(getWords(["meep*"]))

实际上,它接受一个单词列表并检查*,用字符列表astric中的每个字符替换它,并递归进一步的*

你可以记下每个星号的索引

asterisk_location = [i for i, x in enumerate(source) if x == "*"]

您可以利用itertools.product来处理根据出现的星号数生成所有可能的重复对

product(astric, repeat=len(asterisk_location))

然后,您可以将已知星号索引中的每个值替换为itertools生成的值之一

source[index] = value

总之,你最终会得到这样的结果:

from itertools import product
from typing import Generator

astric = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
          'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
          'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']


def generate_possible_options(source: str) -> Generator[str, None, None]:
    source = list(source)
    asterisk_location = [i for i, x in enumerate(source) if x == "*"]
    for option in product(astric, repeat=len(asterisk_location)):
        for index, value in zip(asterisk_location, option):
            source[index] = value
        yield ''.join(source)


if __name__ == '__main__':
    for possibility in generate_possible_options("m*ep*"):
        print(possibility)

当然,您可以添加用户输入并将结果传递给generate_possible_options函数,但我将其保留为静态值,以便可以轻松复制和运行,而无需挂起用户输入

这产生了1296种可能的选择

缩略输出:

maepa
maepb
maepc
maepd
maepe
maepf
maepg
maeph
maepi
maepj
maepk
maepl
...
m9ep2
m9ep3
m9ep4
m9ep5
m9ep6
m9ep7
m9ep8
m9ep9

还可以通过以下方式获取列表对象:

possibilities = list(generate_possible_options("m*ep*"))

这应该起作用:

astric = ['a', 'b', 'c', 'd', 'e', 'f', 'g','h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
usern = input("username you want to check with '*' for unknown chars: ")
paramsGet = {"Name": usern}

def get(usern):
    if len(usern) == 0:
        yield ''
        return
    head, tail = usern[0], usern[1:]
    for each in get(tail):
        if head == '*':
            for c in astric:
                yield c + each
        else:
            yield head + each

for each in get(usern):
    print(each)

我认为这不是最好的办法,也不是最快的办法

相关问题 更多 >