python - 高效地重写简单的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 选项进行优化,但我不知道该怎么做。
解决方案
如果您正在寻找优化,请使用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) )
如果文件确实很大,您可以更改第二个参数(映射的字节大小)以更好地满足您的需求。
推荐阅读
- reactjs - 反应解构状态分配
- javascript - Svelte JS:在另一个方法中实现 onDestroy 的目的是什么
- sql-server - VBA 运行读取文件然后上传到文件到 SQL 表时出现运行时错误 3265
- django - MultipleObjectsReturned at /cart/ get() 返回了多个订单——它返回了 3
- c# - 使用 AutoMapper 通过匹配 ID 映射到列表中的元素
- c# - 无法访问通过 Windows 服务启动的 Rest 服务中的 HEY_CURRENT_USER 环境变量
- azure - 在 Azure 中选择哪种容器服务
- html - 如何使用 svg 和文本内联显示
- mysql - MySQL 中的 INSTR() 可以从索引中受益吗?
- express - 为什么来自axios的响应.then不能改变变量的值