0

我对 python 还很陌生,从我的脚本中获得“完美结果”时遇到了一些麻烦。

到目前为止,这是我的代码:

#import urllib2
#file = urllib2.urlopen('https://server/Gin.txt')
Q = raw_input('Search for: ')

if len(Q) > 0:
        for line in open('Gin.txt'):    #Will be corrected later..
                if Q.lower() in line.lower():
                        print line 

                #print "Found nothing. Did you spell it correct?" ## problem here. 
else:
        os.system('clear')
        print "You didn't type anything. QUITTING!"

现在代码正在运行。它会找到我正在寻找的东西,但是如果它没有找到匹配项。我希望它打印“一无所获......”我得到了各种结果,混合匹配的假阳性结果等等......几乎所有的结果都没有。对你们大多数人来说,这可能是小菜一碟,但我已经工作了 8 个多小时,所以现在我在这里。

如果有更优化/更简单/更漂亮的编写方式,请随时纠正我的错误。我的目标是完美!所以我是所有的眼睛和耳朵。供参考。gin.txt包含从!#_'[] 0..9大写字母到大写字母的几乎所有内容

4

1 回答 1

4

for循环有一个子句else:。当您没有提前结束循环时执行它:

for line in open('Gin.txt'):    #Will be corrected later..
    if Q.lower() in line.lower():
        print line 
        break
else:
    print "Found nothing. Did you spell it correct?"

注意break; 通过跳出for循环,else:套件不会被执行。

这当然会在第一场比赛中停止。如果您需要查找多个匹配项,您唯一的选择是使用某种形式的标志变量:

found = False
for line in open('Gin.txt'):    #Will be corrected later..
    if Q.lower() in line.lower():
        found = True
        print line 

if not found:
    print "Found nothing. Did you spell it correct?"
于 2013-03-29T12:43:59.807 回答