[Python]re+mmap实现大文件的正则匹配
2011-10-12 23:16
477 查看
一、需求
在Python中,要将正则表达式应用于匹配整个文件,但又不想将整个文件内容全部读入内存(特别是对于大文件而言,更是如此)。
二、解决方法
使用re模块进行正则匹配,使用mmap模块进行文件的内存映射。
三、举例
(来源于"Stack Overflow" -- How do I re.search or re.match on a whole file without reading it all into memory?)
You can use mmap to map the file to memory. The file contents can then be accessed like a normal string:
This also works for big files, the file content is internally loaded from disk as needed.
四、参考
re模块和mmap模块的详细介绍请参见Python帮助文档。
在Python中,要将正则表达式应用于匹配整个文件,但又不想将整个文件内容全部读入内存(特别是对于大文件而言,更是如此)。
二、解决方法
使用re模块进行正则匹配,使用mmap模块进行文件的内存映射。
三、举例
(来源于"Stack Overflow" -- How do I re.search or re.match on a whole file without reading it all into memory?)
You can use mmap to map the file to memory. The file contents can then be accessed like a normal string:
import re, mmap with open('/var/log/error.log', 'r+') as f: data = mmap.mmap(f.fileno(), 0) mo = re.search('error: (.*)', data) if mo: print "found error", mo.group(1)
This also works for big files, the file content is internally loaded from disk as needed.
四、参考
re模块和mmap模块的详细介绍请参见Python帮助文档。
相关文章推荐
- 使用python实现正则匹配检索远端FTP目录下的文件
- python实现文件比较,匹配域名
- python re模块实现正则表达式
- 【Python3 爬虫】09_正则表达式(re.math()、re.search()、re.sub()、全局匹配函数)
- Python实现正则表达式匹配任意的邮箱
- Python使用正则匹配实现抓图代码分享
- Python正则匹配递归获得给出目录下的特定类型的文件小技巧
- 【PYTHON】对整个文件进行正则表达式匹配
- python 正则匹配的re.search 例子
- 在目录及其子目录下寻找匹配的文件的python实现
- python之re模块通过正则表达式实现截取
- python中的re和正则匹配的基础扫盲
- 使用Python正则表达式RE从CSDN博客源代码中匹配出博客信息
- python re 正则表达式总结 匹配指定字符
- Python: 正则表达式匹配多行,实现多行匹配模式
- python之正则匹配文件内容
- python3 正则匹配 re.split,re.finditer,re.findall 方法
- 关于python的正则匹配包re的一些经验教训
- Python从文件中读取字符串,用正则表达式匹配中文字符的问题
- Python---对html文件内容进行搜索取出特定URL地址字符串,保存成列表,并使用每个url下载图片,并保存到硬盘上,使用正则re