[英]Problem When Using More Than Two Wildcards
我正在嘗試編寫一個程序,該程序將使用指定的字母和通配符( '*'
),並對照列表中的單詞檢查它們以打印所有可用的匹配項。 我編寫了以下代碼,當使用兩個通配符時,這些代碼將起作用:
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
我的問題是,當使用兩個以上的通配符時,如何編寫此代碼以返回結果? 我嘗試使用下面的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
使用fnmatch.filter
。 基本上,它使用re
模塊實現類似於shell的模式匹配,並且完全可以實現您想要的功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.