Python的结果好坏参半。

2024-04-20 07:39:13 发布

您现在位置: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到大写字母的几乎所有内容


Tags: 代码inimporttxt脚本forifline
1条回答
网友
1楼 · 发布于 2024-04-20 07:39:13

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

相关问题 更多 >