如何显示正则匹配行数

3 投票
2 回答
3302 浏览
提问于 2025-04-16 16:36

我看到过很多关于如何显示行数的例子,也尝试把这些例子用到我的代码里,但都没成功。我是个Python新手,所以我想我还有很多东西需要学习。有没有人能教我怎么在文件中显示找到的匹配项的行数,谢谢?

elif searchType =='3':
      print "Directory to be searched: c:\SQA_log "
      print " "
      directory = os.path.join("c:\\","SQA_log")

      regex = re.compile(r'(?:3\d){6}')
      for root,dirname, files in os.walk(directory):
         for file in files:
           if file.endswith(".log") or file.endswith(".txt"):
              f=open(os.path.join(root,file))
              for line in f.readlines():
                  searchedstr = regex.findall(line)
                  for word in searchedstr:
                     print "String found: " + word
                     print "File: " + os.path.join(root,file)
                     break
                     f.close()

2 个回答

2

可以查看这个链接:http://docs.python.org/library/functions.html#enumerate。把你的循环改成这样,来逐行处理:

for i,line in enumerate(f.readlines()):

这里的i会用来表示行号。

4

好吧,我假设你也想输出行号。为了做到这一点,你可以这样做:

  regex = re.compile(r'(?:3\d){6}')
  for root,dirname, files in os.walk(directory):
     for file in files:
       if file.endswith(".log") or file.endswith(".txt"):
          f=open(os.path.join(root,file))
          for i, line in enumerate(f.readlines()):
              searchedstr = regex.findall(line)
              for word in searchedstr:
                 print "String found: " + word
                 print "Line: "+str(i)
                 print "File: " + os.path.join(root,file)
                 break
          f.close()

撰写回答