如何在不将整个文件加载到字符串(或内存)中的情况下,使用正则表达式(使用re模块)解析大文件?内存映射文件无济于事,因为它们的内容无法转换为某种惰性字符串。 re模块仅支持将字符串用作内容参数。

#include <boost/format.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/regex.hpp>
#include <iostream>

int main(int argc, char* argv[])
{
    boost::iostreams::mapped_file fl("BigFile.log");
    //boost::regex expr("\\w+>Time Elapsed .*?$", boost::regex::perl);
    boost::regex expr("something usefull");
    boost::match_flag_type flags = boost::match_default;
    boost::iostreams::mapped_file::iterator start, end;
    start = fl.begin();
    end = fl.end();
    boost::match_results<boost::iostreams::mapped_file::iterator> what;
    while(boost::regex_search(start, end, what, expr))
    {
        std::cout<<what[0].str()<<std::endl;
        start = what[0].second;
    }
    return 0;
}

展示我的要求。我使用C++(和boost)编写了一个简短的示例,该示例与我想在Python中使用的示例相同。

最佳答案

现在一切正常(Python 3.2.3与Python 2.7的界面有所不同)。搜索模式应仅以b“开头,以提供有效的解决方案(在Python 3.2.3中)。

import re
import mmap
import pprint

def ParseFile(fileName):
    f = open(fileName, "r")
    print("File opened succesfully")
    m = mmap.mmap(f.fileno(), 0, access = mmap.ACCESS_READ)
    print("File mapped succesfully")
    items = re.finditer(b"\\w+>Time Elapsed .*?\n", m)
    for item in items:
        pprint.pprint(item.group(0))

if __name__ == "__main__":
    ParseFile("testre")

关于python - 用re解析Python大文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11674376/

10-09 15:18
查看更多