分析具有非常量格式(值的数目)的文件

Parse a file with non-constant format (number of values)

本文关键字:文件 格式 非常 常量      更新时间:2023-10-16

我目前正在尝试解析一个格式如下的文本文件:

 [value1(double),value2(double];[value1(double),value2(double];...;[value1(double),value2(double]n
 [value1(double),value2(double];[value1(double),value2(double];...;[value1(double),value2(double]n
 etc...

该文件是传感器测量的结果:每个括号thingy表示传感器的值的间隔,每个不同的行表示一个测量。

问题是,我们有时会关闭某些传感器,所以文件的格式不会相同,所以我真的不知道如何做一个"通用"解析器,它不应该考虑打开的传感器的数量。

当然,我不知道是否清楚,不同文件的值数量不同。我的意思是,在同一个文件中,值的数量显然是恒定的。因此,如果我关闭除一个传感器外的每个传感器,我会得到这样的东西:

 [value1(double),value2(double]n
 [value1(double),value2(double]n
 etc...

输出格式为:

LINE 1:
    x1min: ... (first value of the first bracket-couple)
    x1max: ... (second value of the second bracket-couple)
    x2min: ...
    x2max: ...
etc...
LINE 2:
    same here
ETC
enter code here

如果能提供一些帮助,我们将不胜感激。

祝你今天愉快,非常感谢。

PS:很抱歉我的英语不好

读取一行:

 [value1,value2];[value1,value2];[value1,value2];.........

处理生产线:

Till the end of line is met do:
    For all chars from '[' to ']', read the 2 values.
    Store val1 and val2

重复此操作,直到文件结束。

BoostSpirit提供了一个成熟的解析工具:这里有一些代码可以使用并适应您的特定问题:

#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include <vector>
#include <string>
#include <iostream>
namespace client
{
    using namespace std;
    typedef pair<string, double> t_named_num;
    typedef vector<t_named_num> t_named_numbers;
    typedef vector<t_named_numbers> t_records;
    namespace qi = boost::spirit::qi;
    template <typename Iterator>
    struct parse_records : qi::grammar<Iterator, t_records()>
    {
        parse_records() : parse_records::base_type(records)
        {
            name = qi::char_("a-zA-Z_") >> *qi::char_("a-zA-Z_0-9");
            named_num = name >> '(' >> qi::double_ >> ')'    ;
            named_numbers = '[' >> (named_num  % ',') >> ']' ;
            records = named_numbers % ';' ;
        }
        qi::rule<Iterator, string()> name;
        qi::rule<Iterator, t_named_num()> named_num;
        qi::rule<Iterator, t_named_numbers()> named_numbers;
        qi::rule<Iterator, t_records()> records;
    };
}
int main(int argc, char *argv[])
{
    using namespace std;
    using namespace client;
    string s("[a(1),b(2),c(3)];[u(31.5),v(32),z(-23)]");
    string::iterator i = s.begin(), e = s.end();
    parse_records<string::iterator> p;
    t_records c;
    if (boost::spirit::qi::parse(i, e, p, c))
    {
        for (t_records::iterator r = c.begin(); r != c.end(); ++r)
        {
            cout << "record" << endl;
            for (t_named_numbers::iterator n = r->begin(); n != r->end(); ++n)
                cout << n->first << ':' << n->second << endl;
        }
        if (i == e)
            cout << "ok" << endl;
        else
            cout << "ko" << endl;
    }
    else
        cout << "??" << endl;
}

程序输出:

record
a:1
b:2
c:3
record
u:31.5
v:32
z:-23
ok

我必须说,它不容易使用,但实际上是非常非常强大。HTH

您可以读取第一行,计算开括号"["的数量,然后从此设置一个固定长度的解析器。