首页 > 解决方案 > 高效地重写简单的python代码

问题描述

我有以下代码,很可能会重复。意思是,我需要在代码的不同部分搜索整个日志文件,以查看其中是否存在两种特定模式。我不能总是在代码开始时立即搜索模式。

但基本上,以下是我所拥有的,我正在寻找优化它的方法。假设正在读取的日志文件可能非常大。

    textfile = open(logfile, 'r')
    filetext = textfile.read()
    textfile.close()
    matchesBegin = re.search(BeginSearchDVar, filetext)
    matchesEnd = re.search(EndinSearchDVar, filetext)
    if matchesBegin is not None and matchesEnd is not None:
        LRangeA = SeeIfExactRangeIsFound()
        PatternCount = len(LRangeA)
        LRange = '\n'.join(LRangeA)

我知道这可以使用 with 选项进行优化,但我不知道该怎么做。

标签: python

解决方案


如果您正在寻找优化,请使用mmap module.

内存映射文件使用操作系统虚拟内存系统直接访问文件系统上的数据,而不是使用普通的 I/O 函数。内存映射通常会提高 I/O 性能,因为它不涉及每次访问的单独系统调用,并且不需要在缓冲区之间复制数据 - > 内存由内核和用户应用程序直接访问。

import mmap
import re

# Create pattern with all, ignore case, and multi line flags.
# search for every instance of `stackoverflow` within a sentence.
pattern =  re.compile( rb'(\.\W+)?([^.]?stackoverflow[^.]*?\.)',
                       re.DOTALL | re.IGNORECASE | re.MULTILINE )

# open file using 'with' which initializes and finalizes an instance
with open( log_file, "r" ) as file:
    # create new instance of mmap
    with mmap.mmap( file.fileno(), # fileno returns file descriptor for IO
                    0, # size in bytes for how much to map (if 0 then entire file)
                    access = mmap.ACCESS_READ # set access flag to read
                  ) as m: # name instance `m`
        matches = pattern.findall( m ) # find all patterns in mapped file
        print( "Matches: " + len( matches ) )
        for match in matches:
            print( match.group(0) )

如果文件确实很大,您可以更改第二个参数(映射的字节大小)以更好地满足您的需求。


推荐阅读