2013-03-29 73 views
0

我对python还是比较新的,我从脚本中获得“完美结果”时遇到了一些麻烦。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

一个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?" 
+0

(+1)值得注意的是,然而,这并不等同于OP的代码,如果有多场比赛。 – NPE

+0

@Martijn感谢您的回答。简短而正是我需要的。 – jacko