Python:在文件中查找正则表达式 [英] Python: find regexp in a file

查看:30
本文介绍了Python:在文件中查找正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有:

f = open(...)  
r = re.compile(...)

需要:
在大文件中查找第一个匹配正则表达式的位置(开始和结束)?
(从 current_pos=... 开始)

我该怎么做?

我想要这个功能:

def find_first_regex_in_file(f, regexp, start_pos=0):  
   f.seek(start_pos)  

   .... (searching f for regexp starting from start_pos) HOW?  

   return [match_start, match_end]  

文件f"应该很大.

推荐答案

搜索大文件的一种方法是使用 mmap 库将文件映射到大内存块中.然后你可以搜索它而无需明确阅读.

One way to search through big files is to use the mmap library to map the file into a big memory chunk. Then you can search through it without having to explicitly read it.

例如,类似于:

size = os.stat(fn).st_size
f = open(fn)
data = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)

m = re.search(r"867-?5309", data)

这适用于非常大的文件(我已经为 30+ GB 的文件完成了此操作,但如果您的文件超过 1 或 2 GB,则需要 64 位操作系统).

This works well for very big files (I've done it for a file 30+ GB in size, but you'll need a 64-bit OS if your file is more than a GB or two).

这篇关于Python:在文件中查找正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆