Python脚本,用于根据文件中的匹配字符串计算文件夹中的文件数

时间:2014-07-31 11:22:38

标签: python bash perl

我有一个包含多个文件的文件夹。我想计算包含匹配文本的文件数量" Pathology"或模式说" ORC ||||| xxxxxxxx ||||||"在文件夹内的文件里面。我尝试过以下脚本:

import re, os
import glob

list_of_files = glob.glob('./*.hl7')

for fileName in list_of_files:
    fin = open( fileName, "r" )
    count = 0

for line in fin:
    if re.match("Pathology", line):
            count +=1
fin.close()

print count

这给我的结果为0.我使用的是python 2.6.6。并没有升级我的python的选项。请建议一种方法。

3 个答案:

答案 0 :(得分:1)

如果您接受Perl解决方案,那么这符合要求。

目前,它会打印所有匹配文件的名称。如果您真的只想要计数,请删除第print $ARGV, "\n"

use strict;
use warnings;

local @ARGV = glob './*.hl7';

my $count;

while (<>) {
  next unless /Pathology/i;
  ++$count;
  print $ARGV, "\n";
  close ARGV;
}

print "\n\n$count files found\n";

答案 1 :(得分:1)

您可以使用grepwc

执行此操作
grep Pathology *.hl7 | wc -l

为您提供点击次数。

grep -c Pathology *.hl7

将列出具有匹配的文件,然后列出每个文件的命中数。

答案 2 :(得分:0)

最简单的方法是使用grep --files-with-matches StringOrPattern *.hl7grep -l StringOrPattern *.hl7但是如果您需要在python中执行此操作,则需要修复缩进,因为您发布的当前代码只会报告最后一个匹配的数量文件。

import re, os
import glob

list_of_files = glob.glob('./*.hl7')
files_with_matches = 0

for fileName in list_of_files:
    fin = open( fileName, "r" )
    count = 0

    for line in fin:
        if re.match("Pathology", line):
            count +=1
    fin.close()

    if count > 0:
        files_with_matches += 1
        print filename, count

print "Done", files_with_matches, "Matches"
相关问题