Python语句不打印除外

时间:2013-11-27 07:05:01

标签: python python-3.x

当用户没有输入“?”时,无法获取打印的语句。或者输入无效。

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 个答案:

答案 0 :(得分:1)

盲目捕捉异常是一种糟糕的做法。实际上,您根本不需要使用异常处理。

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 '?'")

答案 1 :(得分: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()