使用C++检查 CSV 数据

FIltering CSV data using C++

本文关键字:数据 CSV 检查 C++ 使用      更新时间:2023-10-16

很抱歉问了一个许多人可能认为已经问过的问题。

我有一个很长的 CSV 数据文件 (dat.csv),有 5 列。我还有另一个包含 1 列的短 CSV(过滤器.csv)文件。

现在,我只需要从 dat 中提取列.csv其中列 1 与 filter.csv 的第 1 列匹配。

我通常会使用 sed/awk 在 BASH 中执行此操作。但是,由于其他一些原因,我需要在C++文件中执行此操作。你能建议一种有效的方法来做到这一点吗?

示例数据:

数据.csv

ID,Name,CountryCode,District,Population
3793,NewYork,USA,NewYork,8008278
3794,LosAngeles,USA,California,3694820
3795,Chicago,USA,Illinois,2896016
3796,Houston,USA,Texas,1953631
3797,Philadelphia,USA,Pennsylvania,1517550
3798,Phoenix,USA ,Arizona,1321045
3799,SanDiego,USA,California,1223400
3800,Dallas,USA,Texas,1188580
3801,SanAntonio,USA,Texas,1144646

过滤器.csv

3793
3797
3798

这个.csv排序库可能会有所帮助:

http://www.partow.net/programming/dsvfilter/index.html

您可以将两个表的列合并到一个较大的表中,然后在新表中查询匹配项(其中表 A 的第 1 列和表 B 的第 1 列是)。或者,该库可能具有用于比较表的功能。

以下是一些提示:

  1. 从中读取数据的流需要忽略逗号,因此它应该使用其区域设置中嵌入的std::ctype<char>方面将逗号字符设置为空格。下面是修改分类表的示例:

    struct ctype : std::ctype<char>
    {
    private:
        static mask* get_table()
        {
            static std::vector<mask> v(classic_table(),
                                       classic_table() + table_size);
            v[','] &= ~space;
            return &v[0];
        }
    public:
        ctype() : std::ctype<char>(get_table()) { }
    };
    
  2. 逐行读取第一个 csv. 文件(表示 std::getline() )。提取第一个单词并将其与第二个.csv文件的提取进行比较。继续此操作,直到到达第一个文件的末尾:

    int main()
    {
        std::ifstream in1("test1.csv");
        std::ifstream in2("test2.csv");
        typedef std::istream_iterator<std::string> It;
        in1 >> comma_whitespace;
        in2 >> comma_whitespace;
        std::vector<std::string> in2_content(It(in2), It());
        std::vector<std::string> matches;
        while (std::getline(in1, line))
        {
            std::istringstream iss(line);
            It beg(iss);
            if (std::find(in2_content.begin(),
                          in2_content.end(), *beg) != in2_content.end())
            {
                matches.push_back(line);
            }
        }
    }
    // After the above, the vector matches should hold all the rows that
    // have the same ID number as in the second csv file
    

    comma_whitespace是一个操纵器,它将区域设置更改为上面定义的自定义ctype

    免责声明:我还没有测试过这段代码。