Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何显示找到正则表达式匹配项的行计数_Python_Regex_Count - Fatal编程技术网

Python 如何显示找到正则表达式匹配项的行计数

Python 如何显示找到正则表达式匹配项的行计数,python,regex,count,Python,Regex,Count,我已经看到了几个如何显示行计数的示例,并尝试在代码中实现这些示例,但没有成功。我是一个Python新手,所以我想我还有很多东西要学。有人能告诉我如何显示在文件中找到的匹配的行数吗,谢谢 elif searchType =='3': print "Directory to be searched: c:\SQA_log " print " " directory = os.path.join("c:\\","SQA_log") regex = re

我已经看到了几个如何显示行计数的示例,并尝试在代码中实现这些示例,但没有成功。我是一个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()

好吧,我假设你也想输出行号。为此,您应该:

  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()
看。通过在行上迭代更改循环,如下所示:

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

我将保留行号

行计数?你是说找到这个词的行号?或者匹配单词的行数?最后一个
f.close()
位于一个有趣的位置:)@Spencer Rathbun-找到单词的行号@Aviral Dasgupta-哦,复制、粘贴和试图为公众修改代码可能是危险的…:)!我得到了错误:“无法连接字符串和int对象。”(“行:”+I)。所以,我做了ln=str(I)=>“行:”+ln@user706808哎呀。。。过量服用。现在修好了。应为
+str(i)