简体   繁体   English

使用两个以上通配符时出现问题

[英]Problem When Using More Than Two Wildcards

I am trying to write a program that will take specified letters and wildcard characters( '*' ) and check them against words in a list to print all available matches. 我正在尝试编写一个程序,该程序将使用指定的字母和通配符( '*' ),并对照列表中的单词检查它们以打印所有可用的匹配项。 I have written the below code which will work when two wildcard characters are used: 我编写了以下代码,当使用两个通配符时,这些代码将起作用:

def wildcard_search(letters, count):
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    words = ['hello', 'hi', 'good', 'help', 'hellos', 'helloing', 'hallow', 'no']
    count = 0
    wild_loc = []

    while count < len(letters):
        for letter in letters:
            if letter == '*':
                wild_loc.append(count)
                count += 1

    for letter in alpha:
        new_letters = letters[:wild_loc[1]].replace('*', letter)

        for each in words:
                    each = each.strip('')

            if new_letters in each:
                holder = new_letters

                for letter in alpha:
                    new_letters = letters[wild_loc[1]:].replace('*', letter)

                    for each in words:
                        each = each.strip('')

                        if holder + new_letters in each:
                             print each

My question is, how do I write this code to return results when more than two wildcard characters are used? 我的问题是,当使用两个以上的通配符时,如何编写此代码以返回结果? I have tried using the below while loop, but I end up with an index out of range error: 我尝试使用下面的while循环,但最终出现索引超出范围错误:

count = 0
store = ''
while count <= len(wild_loc)-1:
    for letter in alpha:
        if count != len(wild_loc) - 1:
            new_letter = letters[:wild_loc[count]].replace('*', letter)
            for each in words:
                each = each.strip('')
                if new_letter in each:
                    res = store + new_letter
                    store = new_letter
            count += 1

        elif count == len(wild_loc) - 1:
            new_letter = letters[wild_loc[count]:].replace('*', letter)
            for each in words:
                each = each.strip('')
                if (res + new_letter) in each:
                    print each
            count += 1

Use fnmatch.filter . 使用fnmatch.filter Basically, it implements shell-like pattern matching using the re module , and does exactly what you want. 基本上,它使用re模块实现类似于shell的模式匹配,并且完全可以实现您想要的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM