如何使用 TokenizeBoost 库对 CSV 文件进行标记?

问题描述 投票:0回答:1

我在将任何字符串从 CSV 转换为字符串(但不是字符字符串)然后对其进行标记化时遇到问题。

这里有我的代码:

#include <iostream>
#include <math.h>
#include "NumCpp.hpp"
#include <cstdlib>
#include <python3.10/Python.h>
#include <fstream>      
#include <vector>
#include <string>
#include <algorithm> 
#include <iterator>
#include <boost/tokenizer.hpp>


using namespace std;
using namespace boost;

typedef tokenizer< escaped_list_separator<char> > Tokenizer;
//Take this advice from one site

int main()
{
    string data("DATA.csv");
    ifstream in(data.c_str());

    while (getline(in, line))
    {
        Tokenizer tok(line);
        for (tokenizer<>::iterator beg = tok.begin(); beg != tok.end(); ++beg) {
            cout << *beg << "\n";
        }
    }
    return 0;
}

只是从 CSV 文件中一一复制字符串。

我不知道如何控制这个函数的 tokenize 符号。在官方文档中我只找到了一小段代码,它仅适用于您的字符串变量..

#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>

int main() {
    using namespace std;
    using namespace boost;
    string s = "This is,  a test";
    tokenizer<> tok(s);
    for (tokenizer<>::iterator beg = tok.begin(); beg != tok.end(); ++beg) {
        cout << *beg << "\n";
    }
}

simple_example_1 的输出是:Live

This
is
a
test

我接受您关于标记器不同参数的建议,以及如何解决从 csv 读取标记化的问题。

csv machine-learning visual-c++ boost boost-tokenizer
1个回答
0
投票

首先,不要(永远)这样做:

using namespace std;
using namespace boost;

这会导致至少十几个名称冲突。一般来说,避免

using namespace

问题

您将

Tokenizer
用作:

using Tokenizer = boost::tokenizer<boost::escaped_list_separator<char>>;

这意味着它使用

escaped_list_separator
作为分隔符。您可以使用默认构造函数以外的其他构造函数来将初始值设定项传递给它:

例如

    Tokenizer tok(line, {"\\", ",", "\""});

完整示例:Live

#include <iostream>
#include <fstream>      
#include <boost/tokenizer.hpp>

using Sep       = boost::escaped_list_separator<char>;
using Tokenizer = boost::tokenizer<Sep>;

int main() {
    std::ifstream in("DATA.csv");

    std::string line;

    while (getline(in, line)) {
        Tokenizer   tok(line, {"\\", ",", "\""});
        for (auto beg = tok.begin(); beg != tok.end(); ++beg)
            std::cout << *beg << "\n";
    }
}

如果您不想/不需要转义逻辑,请使用另一个分隔符类,例如https://www.boost.org/doc/libs/1_63_0/libs/tokenizer/char_separator.htm

进一步阅读

有时标记化还不够。考虑编写一个解析器:

© www.soinside.com 2019 - 2024. All rights reserved.