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
开发者_C百科 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:
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
. Basically, it implements shell-like pattern matching using the re
module, and does exactly what you want.
精彩评论