如何使用正则表达式解析大文件(使用re
模块),而不需要将整个文件加载到字符串(或内存)中?内存映射文件不起作用,因为它们的内容不能转换为某种惰性字符串。 re
模块仅支持字符串作为内容参数。解析Python大文件
#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相同。
除非你需要多行的正则表达式,一行解析文件行。 – Lenna 2012-07-26 17:06:04
或许,如果你改写了一个问题,你有什么,以及你想达到什么,它会给我们一个更好的机会来提出建议 - 除非你坚持一种特定的方法。 – 2012-07-26 17:08:28