2011-04-18 13 views
0

我正在尝试编写一个程序,它将采用指定的字母和通配符('*'),并根据列表中的单词检查它们以打印所有可用的匹配项。我已经写了下面的代码,当两个使用通配符,这将工作:使用多于两个通配符时的问题

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 
+3

你可以使用正则表达式或['fnmatch.filter'](http://docs.python.org/library/fnmatch.html#fnmatch.filter)吗?它会更好地工作,我肯定会更快。 – chmullig 2011-04-18 19:38:30

+0

对chmullig的回答+1,最坏的情况下,你可以“预处理”搜索字符串并将其转换为正则表达式。例如,你可能不希望用户必须指定完整的正则表达式,所以你告诉他们在任何字符匹配中使用“*”,然后用*替换输入字符串中的所有*并执行正则表达式搜索。 – DarinH 2011-04-18 19:45:37

+0

+1 chmullig,'fnmatch.filter'确实有效。谢谢我偶然发现了'fnmatch',但是直到现在还没有办法让它工作。 – Timmay 2011-04-18 20:03:28

回答

1

使用fnmatch.filter。基本上,它使用re module实现了类似shell的模式匹配,并且完全按照您的要求进行。