如何使用正則表達式解析大文件(使用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