2011-08-24 19 views
2

有人能帮助我思考解决此问题的方法吗?在下面的代码中,我列出并打开所有.log和.txt文件,以搜索特定的字符串。在最内部的for循环中,有一个if和else语句确定是否找到字符串。我想计算一个字符串在...中匹配的文件的数量,并通过某种方式将它传递给第三个(最后一个)for循环并显示...(例如,匹配的文件:4)。我仍然在学习python,所以我不知道所有可以加速这种努力的不同结构。我确信这是一个非常简单的问题,但除了死记硬背之外,我已经耗尽了我所知道的一切。谢谢!如何获得循环范围中的值并在Python的循环外部使用它

... 

for afile in filelist: 
    (head, filename) = os.path.split(afile) 
    if afile.endswith(".log") or afile.endswith(".txt"): 
     f=ftp.open(afile, 'r') 
     for i, line in enumerate(f.readlines()): 
      result = regex.search(line) 
      if result: 
       ln = str(i) 
       pathname = os.path.join(afile) 
       template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n" 
       output = template.format(ln, pathname, result.group()) 
       hold = output 
       print output 
       ftp.get(afile, 'c:\\Extracted\\' + filename) 
       temp.write(output) 
       break 
     else: 
      print "String Not Found in: " + os.path.join(afile) 
      temp.write("\nString Not Found: " + os.path.join(afile)) 

     f.close() 
for fnum in filelist: 
    print "\nFiles Searched: ", len(filelist) 
    print "Files Matched: ", count 
    num = len(filelist) 

    temp.write("\n\nFiles Searched: " + '%s\n' % (num)) 
    temp.write("Files Matched: ") # here is where I want to show the number of files matched 
    break 
+0

我认为你的格式化是关闭的,或者你犯了一个错误。看起来'else'语句应该和'If结果'排在一起 - 因为它似乎是当正则表达式不匹配的时候。 – Gerrat

+2

'else'应该与'for'对齐。如果'for'循环中的'break'语句永远不会被执行,这将意味着正则表达式不匹配文件中的任何行。 –

回答

4

如何:

count = 0 
for afile in filelist: 
    (head, filename) = os.path.split(afile) 
    if afile.endswith(".log") or afile.endswith(".txt"): 
     f=ftp.open(afile, 'r') 
     for i, line in enumerate(f.readlines()): 
      result = regex.search(line) 
      if result: 
       count += 1 
       ln = str(i) 
       pathname = os.path.join(afile) 
       template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n" 
       output = template.format(ln, pathname, result.group()) 
       hold = output 
       print output 
       ftp.get(afile, 'c:\\Extracted\\' + filename) 
       temp.write(output) 
       break 
     else: 
      print "String Not Found in: " + os.path.join(afile) 
      temp.write("\nString Not Found: " + os.path.join(afile)) 

     f.close() 
for fnum in filelist: 
    print "\nFiles Searched: ", len(filelist) 
    print "Files Matched: ", count 
    num = len(filelist) 

    temp.write("\n\nFiles Searched: " + '%s\n' % (num)) 
    temp.write("Files Matched: "+str(count)) # here is where I want to show the number of files matched 
    break 

数从0开始,增量为每个文件有一个匹配。

+1

我认为你的意思是'count + = 1'。 – zeekay

+1

是的,你是对的。固定。 –

+0

@加布里埃尔 - 谢谢!我认为这是一个直接的解决方案,甚至试图计数+ = 1,但将其放置在错误的位置。 – suffa