一次计算匹配不同图案的线条数

2024-09-24 22:27:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本,给定的模式遍历一个文件,对于与它保存的模式匹配的每一行,计算该行在文件中出现的次数。在

脚本如下:

#!/usr/bin/env python

import time
fnamein = 'Log.txt'

def filter_and_count_matches(fnamein, fnameout, match):
  fin = open(fnamein, 'r')
  curr_matches = {}
  order_in_file = [] # need this because dict has no particular order
  for line in (l for l in fin if l.find(match) >= 0):
    line = line.strip()
    if line in curr_matches:
      curr_matches[line] += 1
    else:
      curr_matches[line] = 1
      order_in_file.append(line)
  #
  fout = open(fnameout, 'w')
  #for line in order_in_file:
  for line, _dummy in sorted(curr_matches.iteritems(),
      key=lambda (k, v): (v, k), reverse=True):
    fout.write(line + '\n')
    fout.write(' = {}\n'.format(curr_matches[line]))
  fout.close()

def main():
  for idx, match in enumerate(open('staffs.txt', 'r').readlines()):
    curr_time = time.time()
    match = match.strip()
    fnameout = 'm{}.txt'.format(idx+1)
    filter_and_count_matches(fnamein, fnameout, match)
    print 'Processed {}. Time = {}'.format(match, time.time() - curr_time)

main()

所以现在每次我想检查一个不同的模式时,我都会检查这个文件。 可以只检查一次文件(文件非常大,因此需要一段时间来处理)。如果能以一种优雅的“轻松”的方式来做这件事,那就太好了。谢谢!在

谢谢


Tags: 文件intxtfortimematchlineorder
1条回答
网友
1楼 · 发布于 2024-09-24 22:27:14

似乎^{}可以满足您的需要:

from collections import Counter
lines = Counter([line for line in myfile if match_string in line])

例如,如果myfile包含

^{pr2}$

并且match_string是{},那么上面的代码给出了

>>> lines
Counter({'123abc': 2, 'abc456': 2})

对于多个模式,可以这样做:

patterns = ["abc", "123"]
# initialize one Counter for each pattern
results = {pattern:Counter() for pattern in patterns}  
for line in myfile:
   for pattern in patterns:
       if pattern in line:
           results[pattern][line] += 1

相关问题 更多 >