使用C++检查 CSV 数据
FIltering CSV data using C++
很抱歉问了一个许多人可能认为已经问过的问题。
我有一个很长的 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 列是)。或者,该库可能具有用于比较表的功能。
以下是一些提示:
-
从中读取数据的流需要忽略逗号,因此它应该使用其区域设置中嵌入的
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()) { } };
-
逐行读取第一个 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
。免责声明:我还没有测试过这段代码。
相关文章:
- 如何从 CSV 获取数据并将其存储在 C++ 中的表对象中
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 读取和存储 CSV 数据
- 如何将csv中的数据放入c++中的字符串向量中,而绝对没有任何作用
- CSV文件未从缓冲区获取数据
- 错误的值是使用c++从CSV文件数据写入数组
- 将数据从CSV字符串转换为浮点值
- 对来自csv文件的数据执行OpenCV k-means
- std::fstream 需要很长时间才能将大数据写入.csv文件中
- 从第 x 列提取到 y 列,从第 1 行到第 2 行提取 csv 数据 c++
- C++ 读取.csv文件,将数据放入变量中,然后放入对象中
- 如何多次写入.CSV文件并使用C 保留先前的数据
- 用于读取C 中的CSV的数据结构
- 从 CSV 文件读取并尝试将数据加载到由结构组成的矢量中
- 从 csv 文件中获取不同类型的数据,并将其放入 C++ 中的 typedef 结构中
- 尝试从 csv 文件输入大量数据时出错
- C++从 csv 文件中读取,然后将数据分配给类成员
- C++从 CSV 读取的实时数据
- QT自动使用CSV的数据生成按钮
- C :如何将数据作为CSV输出到现有文件中的一组特定单元格