2010-07-02 181 views
0

我需要知道下面的情况下,最好的办法Python的解析文件

可以说,我们有记录的编译输出一些巨大的文件,并有几个错误模式,我要测试的此文件,例如。错误模式可能是

- : error: 
- : error [A-Z]*[\d ]* 
- [A-Z]*[\d]* [E\e|rror: 
- " Cannot open include file " 
- " Could not find " 
- "is not a member of" 
- "has not been declared" 

让我知道这将是有效的:

  • 倾倒在一些变量的文件,并关闭文件
  • grep命令从列表中的每个错误
  • 或为每个错误创建正则表达式并通过变量解析

谢谢

+0

No.(十二个) – 2010-07-02 19:59:19

回答

2

如果日志文件很大,它可能不会将其加载到内存是个好主意。相反,你可以预编译所有的正则表达式和测试对他们一行行,如:

def has_error(filename): 
    with file(filename, 'r') as logfile: 
     for line in logfile: 
      for regexp in MY_REGEXPS: 
       if regexp.search(line): 
        return True 
     return False 
0

鉴于日志文件很大,检查错误的(更有效的)方法是一次遍历文件一行,并根据模式检查每行。您不希望在内存中占用大量文件。

在Python,大概是这样的:

err = re.compile(': error(?::| [A-Z]*[\d ]*)|[A-Z]*\d* [Ee]rror:|' + 
       '" (?:Cannot open include file|Could not find) "|' + 
       '"(?:is not a member of|has not been declared)"') 
with open('file.log') as f: 
    for line in f: 
     m = err.search(line) 
     if m is not None: 
      # this line indicates an error 

虽然你可能需要改变正则表达式来满足您的需求。另一种方法是获得一个静态字符串列表,例如

err_list = ['error', 'Cannot open include file', 'Could not find', 'is not a member of', 'has not been declared'] 

,只是搜索在每行每串:

with open('file.log') as f: 
    for line in f: 
     if any(line.find(e) for e in err_list): 
      # this line indicates an error 
0

,你正在阅读一个巨大的数据到内存的量,然后尝试操作上这真的不是非常有效它。除非你有大量的记忆,否则这可能不是一个好主意。

使用,而不是一台发电机:

def parser(filename): 
    with open(filename, 'r') as f: # For use in python > 2.4 I *think*. 
     for line in f: 
      if anymatches(line): # or whatever you want to do to generate a 
       yield line  # true/false value 

这将不加载整个文件到内存中,也只有当你问他们生产火柴的好处 - 如果你只想要第一个N所以匹配你可以这样做:

for i, match in zip(xrange(N), parser('mylogfile')): 
    #do something with match