2013-11-27 146 views
0

当用户没有输入'?'时,无法获得要打印的语句。或者进行无效输入。Python语句不打印

def crossWord(): 
    try: 
     word = strInput("Crossword Solver \nuse ? as a wildcard: ") 
     w = word.lower() 
     f=open("wordlist.txt", "r") 
     for line in f: 
      line=line.strip() 
      if len(line)==len(w): 
       good=1 
       pos=0 
       for letter in w: 
        if not letter== '?': 
         if not letter==line[pos]: 
          good=0 
        pos+=1 
       if good==1: 
        print(line) 
    except: 
     if line == None: 
      print("No words could be found. Remember to separate with '?'") 
    finally: 
     f.close() 
+2

你不会抛出异常。你从'except'期待什么? – Mailerdaimon

+0

另外一行不在其范围之内。它在try中被分配,而不是在它之外被声明。 – scriptmonster

+0

如果用户输入无效,我需要它来打印该语句。没有除外,我不知道该怎么做。 – user3040301

回答

0
try: 
    word = strInput("Crossword Solver \nuse ? as a wildcard: ") 
    w = word.lower() 
    f = open("wordlist.txt", "r") 
    for line in f: 
     line = line.strip() 
     if len(line)==len(w): 
      for pos,letter in enumerate(w): 
       if letter != '?' and letter != line[pos]: 
        raise  
except: 
    print("No words could be found. Remember to separate with '?'") 
else: 
    print(line) 
finally: 
    f.close() 
1

捕获异常blinly是个不错的办法。事实上,你根本不需要使用异常处理。

import re 

def cross_word(): 
    with open('wordlist.txt') as dict_fp: 
     dictionary = [line.strip().lower() for line in dict_fp] 
    word = input("Crossword Solver\nuse ? as wildcard: ") 
    pattern = re.compile('^'+''.join(('.' if c=='?' else re.escape(c)) for c in word)+'$') 
    matches = [w for w in dictionary if pattern.match(w)] 
    if matches: 
     for found in matches: 
      print(found) 
    else: 
     print("No words could be found. Remeber to separate with '?'")