高效读取 3MB 文本文件,包括。解析

Efficient read of a 3MB text file incl. parsing

我有几个 ~3MB 的文本文件需要用 C++ 解析。

文本文件如下所示 (1024x786):

12,23   45,78   90,12   34,56   78,90   ...
12,23   45,78   90,12   34,56   78,90   ...
12,23   45,78   90,12   34,56   78,90   ...
12,23   45,78   90,12   34,56   78,90   ...
12,23   45,78   90,12   34,56   78,90   ...

表示 "number blocks" 由 Tab 分隔,数字本身包含 ,(代替 .)小数点标记。

首先我需要阅读文件。目前我正在使用这个:

#include <boost/tokenizer.hpp>

string line;
ifstream myfile(file);
if (myfile.is_open())
{
    char_separator<char> sep("\t");
    tokenizer<char_separator<char>> tokens(line, sep); 
}
myfile.close();

在获取 "number block" 方面效果很好,但我仍然需要将此 char 转换为浮点数,但将 , 处理为小数点标记。由于文件大小,我认为 tokenize 这也不是一个好主意。此外,我需要将所有这些值添加到一个数据结构中,之后我可以按位置访问该数据结构(例如 [x][y])。有什么想法可以实现吗?

我会直接做什么(根本不需要 boost::tokenizer):

std::setlocale(LC_NUMERIC, "de_DE"); // Use ',' as decimal point
std::vector<std::vector<double>> dblmat;
std::string line;
while(std::getline(myfile,line)) {
    dblmat.push_back(std::vector<double>());
    std::istringstream iss(line);
    double val;
    while(iss >> val) {
        dblmat.back().push_back(val);
    } 
} 

您可以使用 Boost.Spirit 来解析文件的内容,作为最终结果,您可以从解析器中获得您喜欢的结构化数据,例如 std::vector<std::vector<float>>。 IMO,您的普通文件的大小并不大。我相信最好将整个文件读入内存并执行解析器。下面 read_file 显示了一种读取文件的有效解决方案。

qi::float_ 解析长度和大小受 float 类型限制的实数,它使用 .(点)作为分隔符。您可以通过 qi::real_policies<T>::parse_dot. Below I am using a code snippet from spirit/example/qi/german_floating_point.cpp.

自定义分隔符

看看这个演示:

#include <boost/spirit/include/qi.hpp>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

std::string read_file(std::string path)
{
    std::string str;
    std::ifstream file( path, std::ios::ate);
    if (!file) return str;
    auto size(file.tellg());
    str.resize(size);
    file.seekg(0, std::ios::beg);
    file.rdbuf()->sgetn(&str[0], size);
    return str;
}

using namespace boost::spirit;

//From Boost.Spirit example `qi/german_floating_point.cpp`
//Begin
template <typename T>
struct german_real_policies : qi::real_policies<T>
{
    template <typename Iterator>
    static bool parse_dot(Iterator& first, Iterator const& last)
    {
        if (first == last || *first != ',')
            return false;
        ++first;
        return true;
    }
};

qi::real_parser<float, german_real_policies<float> > const german_float;
//End

int main()
{
    std::string in(read_file("input"));
    std::vector<std::vector<float>> out;
    auto ret = qi::phrase_parse(in.begin(), in.end(),
                                +(+(german_float - qi::eol) >> qi::eol),
                                boost::spirit::ascii::blank_type{},
                                out);
    if(ret && in.begin() == in.end())
        std::cout << "Success" << std::endl;
}