Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
parse-csv.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
121#ifndef PARSE_CSV_H
122#define PARSE_CSV_H
123
124#include <sstream>
125#include <istream>
126#include <ostream>
127#include <fstream>
128#include <string>
129#include <utility>
130#include <tpl_array.H>
131
132namespace Aleph
133{
134
159inline Array<std::string> csv_read_row(std::istream & in, char delimiter = ',')
160{
161 std::stringstream ss;
162 bool inquotes = false;
163 Array<std::string> row; // Relying on RVO
164
165 while (in.good())
166 {
167 int ch = in.get();
168
169 // Check for EOF
170 if (ch == std::char_traits<char>::eof())
171 break;
172
173 char c = static_cast<char>(ch);
174
175 if (not inquotes and c == '"') // Begin quoted field
176 inquotes = true;
177 else if (inquotes and c == '"') // Quote character inside quoted field
178 {
179 if (in.peek() == '"') // Two consecutive quotes resolve to one
180 ss << static_cast<char>(in.get());
181 else // End of quoted field
182 inquotes = false;
183 }
184 else if (not inquotes and c == delimiter) // End of field
185 {
186 row.append(ss.str());
187 ss.str("");
188 }
189 else if (not inquotes and (c == '\r' or c == '\n')) // End of row
190 {
191 if (in.peek() == '\n') // Handle CRLF
192 in.get();
193 row.append(ss.str());
194 return row;
195 }
196 else
197 ss << c;
198 }
199
200 // Handle last field if stream ended without newline
201 if (ss.str().size() > 0 or row.size() > 0)
202 row.append(ss.str());
203
204 return row;
205}
206
225inline Array<std::string> csv_read_row(const std::string & line,
226 char delimiter = ',')
227{
228 std::stringstream ss(line);
229 return csv_read_row(ss, delimiter);
230}
231
254inline Array<Array<std::string>> csv_read_all(std::istream & in,
255 char delimiter = ',')
256{
258
259 while (in.good())
260 {
261 Array<std::string> row = csv_read_row(in, delimiter);
262 if (row.size() == 0 and not in.good())
263 break;
264 result.append(std::move(row));
265 }
266
267 return result;
268}
269
291inline Array<Array<std::string>> csv_read_file(const std::string & filename,
292 char delimiter = ',')
293{
294 std::ifstream file(filename);
295 if (not file.is_open())
296 throw std::runtime_error("Cannot open file: " + filename);
297
298 return csv_read_all(file, delimiter);
299}
300
321inline std::string csv_escape(const std::string & field, char delimiter = ',')
322{
323 bool needs_quoting = false;
324
325 // Check if quoting is needed
326 for (char c : field)
327 {
328 if (c == delimiter or c == '"' or c == '\n' or c == '\r')
329 {
330 needs_quoting = true;
331 break;
332 }
333 }
334
335 if (not needs_quoting)
336 return field;
337
338 // Escape by quoting and doubling internal quotes
339 std::string result = "\"";
340 for (char c : field)
341 {
342 if (c == '"')
343 result += "\"\"";
344 else
345 result += c;
346 }
347 result += "\"";
348
349 return result;
350}
351
377inline void csv_write_row(std::ostream & out,
378 const Array<std::string> & row,
379 char delimiter = ',',
380 const std::string & line_ending = "\n")
381{
382 for (size_t i = 0; i < row.size(); ++i)
383 {
384 if (i > 0)
385 out << delimiter;
386 out << csv_escape(row(i), delimiter);
387 }
388 out << line_ending;
389}
390
403inline void csv_write_all(std::ostream & out,
405 char delimiter = ',',
406 const std::string & line_ending = "\n")
407{
408 for (size_t i = 0; i < rows.size(); ++i)
409 csv_write_row(out, rows(i), delimiter, line_ending);
410}
411
425inline void csv_write_file(const std::string & filename,
427 char delimiter = ',',
428 const std::string & line_ending = "\n")
429{
430 std::ofstream file(filename);
431 if (not file.is_open())
432 throw std::runtime_error("Cannot open file for writing: " + filename);
433
434 csv_write_all(file, rows, delimiter, line_ending);
435}
436
445[[nodiscard]] inline size_t csv_num_columns(const Array<std::string> & row)
446{
447 return row.size();
448}
449
467[[nodiscard]] inline bool csv_is_rectangular(const Array<Array<std::string>> & rows)
468{
469 if (rows.size() == 0)
470 return true;
471
472 size_t expected_cols = rows(0).size();
473 for (size_t i = 1; i < rows.size(); ++i)
474 if (rows(i).size() != expected_cols)
475 return false;
476
477 return true;
478}
479
499 size_t col_index)
500{
501 Array<std::string> column;
502
503 for (size_t i = 0; i < rows.size(); ++i)
504 {
505 if (col_index >= rows(i).size())
506 throw std::out_of_range("Column index " + std::to_string(col_index) +
507 " out of range for row " + std::to_string(i));
508 column.append(rows(i)(col_index));
509 }
510
511 return column;
512}
513
534template <typename T>
535[[nodiscard]] inline T csv_to_number(const std::string & field)
536{
537 std::istringstream ss(field);
538 T value;
539 ss >> value;
540
541 if (ss.fail())
542 throw std::invalid_argument("Cannot convert '" + field + "' to number");
543
544 return value;
545}
546
547// Template specialization for int (uses std::stoi for better error handling)
548template <>
549[[nodiscard]] inline int csv_to_number<int>(const std::string & field)
550{
551 return std::stoi(field);
552}
553
554// Template specialization for long (uses std::stol for better error handling)
555template <>
556[[nodiscard]] inline long csv_to_number<long>(const std::string & field)
557{
558 return std::stol(field);
559}
560
561// Template specialization for double (uses std::stod for better error handling)
562template <>
563[[nodiscard]] inline double csv_to_number<double>(const std::string & field)
564{
565 return std::stod(field);
566}
567
568// Template specialization for float (uses std::stof for better error handling)
569template <>
570[[nodiscard]] inline float csv_to_number<float>(const std::string & field)
571{
572 return std::stof(field);
573}
574
575//============================================================================
576// CsvRow - Row with header-based access
577//============================================================================
578
602{
605
606public:
609 : fields_(std::move(fields)), header_(nullptr) {}
610
614
616 [[nodiscard]] const std::string & operator[](size_t index) const
617 {
618 return fields_(index);
619 }
620
624 [[nodiscard]] const std::string & operator[](const std::string & column_name) const
625 {
626 if (header_ == nullptr)
627 throw std::runtime_error("No header set for CsvRow");
628
629 for (size_t i = 0; i < header_->size(); ++i)
630 if ((*header_)(i) == column_name)
631 return fields_(i);
632
633 throw std::out_of_range("Column not found: " + column_name);
634 }
635
637 [[nodiscard]] const std::string & at(size_t index) const
638 {
639 if (index >= fields_.size())
640 throw std::out_of_range("Index out of range: " + std::to_string(index));
641 return fields_(index);
642 }
643
645 [[nodiscard]] bool has_column(const std::string & column_name) const
646 {
647 if (header_ == nullptr) return false;
648 for (size_t i = 0; i < header_->size(); ++i)
649 if ((*header_)(i) == column_name)
650 return i < fields_.size();
651 return false;
652 }
653
655 template <typename T>
656 [[nodiscard]] T get(size_t index) const
657 {
658 return csv_to_number<T>(fields_(index));
659 }
660
662 template <typename T>
663 [[nodiscard]] T get(const std::string & column_name) const
664 {
665 return csv_to_number<T>((*this)[column_name]);
666 }
667
669 [[nodiscard]] size_t size() const { return fields_.size(); }
670
672 [[nodiscard]] bool empty() const { return fields_.size() == 0; }
673
675 [[nodiscard]] const Array<std::string> & fields() const { return fields_; }
676
678 [[nodiscard]] const Array<std::string> * header() const { return header_; }
679};
680
681//============================================================================
682// CsvReader - Iterator-based reader for large files
683//============================================================================
684
712{
713 std::ifstream file_;
714 std::istream * stream_;
720
721public:
724 explicit CsvReader(const std::string & filename, char delimiter = ',')
725 : file_(filename), stream_(&file_), owns_stream_(true),
726 delimiter_(delimiter), has_header_(false), row_count_(0)
727 {
728 if (not file_.is_open())
729 throw std::runtime_error("Cannot open file: " + filename);
730 }
731
733 explicit CsvReader(std::istream & stream, char delimiter = ',')
734 : stream_(&stream), owns_stream_(false),
735 delimiter_(delimiter), has_header_(false), row_count_(0) {}
736
747 : file_(std::move(other.file_)),
748 stream_(other.owns_stream_ ? &file_ : std::exchange(other.stream_, &other.file_)),
749 owns_stream_(std::exchange(other.owns_stream_, true)), delimiter_(other.delimiter_),
750 header_(std::move(other.header_)), has_header_(std::exchange(other.has_header_, false)),
751 row_count_(std::exchange(other.row_count_, 0)) {}
752
759 {
760 swap(other);
761 return *this;
762 }
763
768 void swap(CsvReader & other)
769 {
770 file_.swap(other.file_);
771 std::swap(stream_, other.stream_);
772 std::swap(owns_stream_, other.owns_stream_);
773 std::swap(delimiter_, other.delimiter_);
774 header_.swap(other.header_);
775 std::swap(has_header_, other.has_header_);
776 std::swap(row_count_, other.row_count_);
777 if (owns_stream_) // each reader reads its own file, whose state was exchanged
778 stream_ = &file_;
779 if (other.owns_stream_)
780 other.stream_ = &other.file_;
781 }
782
791
793 [[nodiscard]] bool has_next() const
794 {
795 return stream_->good() and stream_->peek() != std::char_traits<char>::eof();
796 }
797
804
807 {
808 ++row_count_;
809 auto fields = csv_read_row(*stream_, delimiter_);
810 if (has_header_)
811 return CsvRow(std::move(fields), header_);
812 return CsvRow(std::move(fields));
813 }
814
816 [[nodiscard]] size_t rows_read() const { return row_count_; }
817
819 [[nodiscard]] const Array<std::string> & header() const { return header_; }
820
822 [[nodiscard]] bool has_header() const { return has_header_; }
823
825 void skip(size_t n)
826 {
827 for (size_t i = 0; i < n and has_next(); ++i)
828 next();
829 }
830
832 void reset()
833 {
834 if (owns_stream_)
835 {
836 file_.clear();
837 file_.seekg(0);
838 row_count_ = 0;
839 if (has_header_)
840 read_header(); // Re-read header
841 }
842 }
843
844 // Iterator support for range-based for loops
846 {
850
851 public:
852 Iterator(CsvReader * reader, bool at_end)
853 : reader_(reader), at_end_(at_end)
854 {
855 if (not at_end_ and reader_->has_next())
856 current_ = reader_->next();
857 else
858 at_end_ = true;
859 }
860
861 const Array<std::string> & operator*() const { return current_; }
862
864 {
865 if (reader_->has_next())
866 current_ = reader_->next();
867 else
868 at_end_ = true;
869 return *this;
870 }
871
872 bool operator!=(const Iterator & other) const
873 {
874 return at_end_ != other.at_end_;
875 }
876 };
877
878 Iterator begin() { return Iterator(this, false); }
879 Iterator end() { return Iterator(this, true); }
880};
881
882//============================================================================
883// Filtering and Selection Functions
884//============================================================================
885
905template <typename Pred>
907 Pred predicate)
908{
910 for (size_t i = 0; i < rows.size(); ++i)
911 if (predicate(rows(i)))
912 result.append(rows(i));
913 return result;
914}
915
929 size_t col_index,
930 const std::string & value)
931{
932 return csv_filter(rows, [col_index, &value](const Array<std::string> & row) {
933 return col_index < row.size() and row(col_index) == value;
934 });
935}
936
955 const Array<size_t> & col_indices)
956{
958
959 for (size_t i = 0; i < rows.size(); ++i)
960 {
961 Array<std::string> new_row;
962 for (size_t j = 0; j < col_indices.size(); ++j)
963 {
964 size_t idx = col_indices(j);
965 if (idx < rows(i).size())
966 new_row.append(rows(i)(idx));
967 else
968 new_row.append(""); // Empty if column doesn't exist
969 }
970 result.append(std::move(new_row));
971 }
972
973 return result;
974}
975
986 size_t n)
987{
989 for (size_t i = n; i < rows.size(); ++i)
990 result.append(rows(i));
991 return result;
992}
993
1003 const Array<Array<std::string>> & rows,
1004 size_t n)
1005{
1007 size_t limit = (n < rows.size()) ? n : rows.size();
1008 for (size_t i = 0; i < limit; ++i)
1009 result.append(rows(i));
1010 return result;
1011}
1012
1013//============================================================================
1014// Statistics Functions
1015//============================================================================
1016
1020[[nodiscard]] inline size_t csv_count_rows(const Array<Array<std::string>> & rows)
1021{
1022 return rows.size();
1023}
1024
1028[[nodiscard]] inline size_t csv_count_empty(const Array<Array<std::string>> & rows)
1029{
1030 size_t count = 0;
1031 for (size_t i = 0; i < rows.size(); ++i)
1032 for (size_t j = 0; j < rows(i).size(); ++j)
1033 if (rows(i)(j).empty())
1034 ++count;
1035 return count;
1036}
1037
1041template <typename Pred>
1042[[nodiscard]] inline size_t csv_count_if(const Array<Array<std::string>> & rows,
1043 Pred predicate)
1044{
1045 size_t count = 0;
1046 for (size_t i = 0; i < rows.size(); ++i)
1047 if (predicate(rows(i)))
1048 ++count;
1049 return count;
1050}
1051
1056template <typename Pred>
1057[[nodiscard]] inline size_t csv_find_row(const Array<Array<std::string>> & rows,
1058 Pred predicate)
1059{
1060 for (size_t i = 0; i < rows.size(); ++i)
1061 if (predicate(rows(i)))
1062 return i;
1063 return rows.size();
1064}
1065
1070[[nodiscard]] inline size_t csv_find_by_value(
1071 const Array<Array<std::string>> & rows,
1072 size_t col_index,
1073 const std::string & value)
1074{
1075 return csv_find_row(rows, [col_index, &value](const Array<std::string> & row) {
1076 return col_index < row.size() and row(col_index) == value;
1077 });
1078}
1079
1084 size_t col_index)
1085{
1086 Array<std::string> result;
1087 for (size_t i = 0; i < rows.size(); ++i)
1088 {
1089 if (col_index >= rows(i).size()) continue;
1090
1091 const std::string & val = rows(i)(col_index);
1092 bool found = false;
1093 for (size_t j = 0; j < result.size(); ++j)
1094 if (result(j) == val) { found = true; break; }
1095
1096 if (not found)
1097 result.append(val);
1098 }
1099 return result;
1100}
1101
1102//============================================================================
1103// Transformation Functions
1104//============================================================================
1105
1115 const Array<Array<std::string>> & rows)
1116{
1117 if (rows.size() == 0)
1118 return Array<Array<std::string>>();
1119
1120 if (not csv_is_rectangular(rows))
1121 throw std::runtime_error("Cannot transpose non-rectangular CSV data");
1122
1123 size_t num_rows = rows.size();
1124 size_t num_cols = rows(0).size();
1125
1127 for (size_t j = 0; j < num_cols; ++j)
1128 {
1129 Array<std::string> new_row;
1130 for (size_t i = 0; i < num_rows; ++i)
1131 new_row.append(rows(i)(j));
1132 result.append(std::move(new_row));
1133 }
1134
1135 return result;
1136}
1137
1148 const Array<Array<std::string>> & rows,
1149 size_t col_index,
1150 bool ascending = true)
1151{
1152 // Create index array
1153 Array<size_t> indices;
1154 for (size_t i = 0; i < rows.size(); ++i)
1155 indices.append(i);
1156
1157 // Sort indices by column value
1158 for (size_t i = 0; i < indices.size(); ++i)
1159 for (size_t j = i + 1; j < indices.size(); ++j)
1160 {
1161 const std::string & a = (col_index < rows(indices(i)).size())
1162 ? rows(indices(i))(col_index) : "";
1163 const std::string & b = (col_index < rows(indices(j)).size())
1164 ? rows(indices(j))(col_index) : "";
1165
1166 bool should_swap = ascending ? (a > b) : (a < b);
1167 if (should_swap)
1168 std::swap(indices(i), indices(j));
1169 }
1170
1171 // Build sorted result
1173 for (size_t i = 0; i < indices.size(); ++i)
1174 result.append(rows(indices(i)));
1175
1176 return result;
1177}
1178
1189template <typename T>
1191 const Array<Array<std::string>> & rows,
1192 size_t col_index,
1193 bool ascending = true)
1194{
1195 // Create pairs of (value, index)
1197 for (size_t i = 0; i < rows.size(); ++i)
1198 {
1199 T val = (col_index < rows(i).size())
1200 ? csv_to_number<T>(rows(i)(col_index)) : T{};
1201 pairs.append({val, i});
1202 }
1203
1204 // Sort pairs
1205 for (size_t i = 0; i < pairs.size(); ++i)
1206 for (size_t j = i + 1; j < pairs.size(); ++j)
1207 {
1208 bool should_swap = ascending
1209 ? (pairs(i).first > pairs(j).first)
1210 : (pairs(i).first < pairs(j).first);
1211 if (should_swap)
1212 std::swap(pairs(i), pairs(j));
1213 }
1214
1215 // Build sorted result
1217 for (size_t i = 0; i < pairs.size(); ++i)
1218 result.append(rows(pairs(i).second));
1219
1220 return result;
1221}
1222
1231 const Array<Array<std::string>> & rows)
1232{
1234
1235 for (size_t i = 0; i < rows.size(); ++i)
1236 {
1237 bool is_duplicate = false;
1238 for (size_t j = 0; j < result.size(); ++j)
1239 {
1240 if (result(j).size() != rows(i).size()) continue;
1241
1242 bool equal = true;
1243 for (size_t k = 0; k < rows(i).size(); ++k)
1244 if (result(j)(k) != rows(i)(k)) { equal = false; break; }
1245
1246 if (equal) { is_duplicate = true; break; }
1247 }
1248
1249 if (not is_duplicate)
1250 result.append(rows(i));
1251 }
1252
1253 return result;
1254}
1255
1265template <typename Func>
1267 const Array<Array<std::string>> & rows,
1268 Func func)
1269{
1271
1272 for (size_t i = 0; i < rows.size(); ++i)
1273 {
1274 Array<std::string> new_row;
1275 for (size_t j = 0; j < rows(i).size(); ++j)
1276 new_row.append(func(rows(i)(j)));
1277 result.append(std::move(new_row));
1278 }
1279
1280 return result;
1281}
1282
1283//============================================================================
1284// Utility Functions
1285//============================================================================
1286
1298inline bool csv_skip_bom(std::istream & in)
1299{
1300 // A byte is taken only when peek() shows that it continues the BOM, and
1301 // given back on a mismatch: reading three bytes and putting them back
1302 // lost the bytes of a stream shorter than three, since the reads failed
1303 // at its end and then so did putback()
1304 constexpr unsigned char bom[] = {0xEF, 0xBB, 0xBF};
1305 size_t taken = 0;
1306 while (taken < 3 and in.peek() == bom[taken])
1307 {
1308 in.get();
1309 ++taken;
1310 }
1311 if (taken == 3)
1312 return true;
1313
1314 for (; taken > 0; --taken)
1315 in.unget();
1316 return false;
1317}
1318
1327 const Array<Array<std::string>> & rows)
1328{
1329 auto trim = [](const std::string & s) -> std::string {
1330 size_t start = 0;
1331 while (start < s.size() and std::isspace(static_cast<unsigned char>(s[start])))
1332 ++start;
1333
1334 size_t end = s.size();
1335 while (end > start and std::isspace(static_cast<unsigned char>(s[end - 1])))
1336 --end;
1337
1338 return s.substr(start, end - start);
1339 };
1340
1341 return csv_transform(rows, trim);
1342}
1343
1353 const Array<Array<std::string>> & rows,
1354 const std::string & default_value)
1355{
1356 return csv_transform(rows, [&default_value](const std::string & s) {
1357 return s.empty() ? default_value : s;
1358 });
1359}
1360
1373 const Array<Array<std::string>> & left,
1374 const Array<Array<std::string>> & right)
1375{
1377 size_t max_rows = (left.size() > right.size()) ? left.size() : right.size();
1378
1379 for (size_t i = 0; i < max_rows; ++i)
1380 {
1381 Array<std::string> new_row;
1382
1383 // Add fields from left
1384 if (i < left.size())
1385 for (size_t j = 0; j < left(i).size(); ++j)
1386 new_row.append(left(i)(j));
1387
1388 // Add fields from right
1389 if (i < right.size())
1390 for (size_t j = 0; j < right(i).size(); ++j)
1391 new_row.append(right(i)(j));
1392
1393 result.append(std::move(new_row));
1394 }
1395
1396 return result;
1397}
1398
1408 const Array<Array<std::string>> & top,
1409 const Array<Array<std::string>> & bottom)
1410{
1412
1413 for (size_t i = 0; i < top.size(); ++i)
1414 result.append(top(i));
1415
1416 for (size_t i = 0; i < bottom.size(); ++i)
1417 result.append(bottom(i));
1418
1419 return result;
1420}
1421
1433 const Array<Array<std::string>> & left,
1434 size_t left_key_col,
1435 const Array<Array<std::string>> & right,
1436 size_t right_key_col)
1437{
1439
1440 for (size_t i = 0; i < left.size(); ++i)
1441 {
1442 if (left_key_col >= left(i).size()) continue;
1443 const std::string & left_key = left(i)(left_key_col);
1444
1445 for (size_t j = 0; j < right.size(); ++j)
1446 {
1447 if (right_key_col >= right(j).size()) continue;
1448
1449 if (left_key == right(j)(right_key_col))
1450 {
1451 // Combine rows (excluding duplicate key from right)
1452 Array<std::string> new_row;
1453
1454 for (size_t k = 0; k < left(i).size(); ++k)
1455 new_row.append(left(i)(k));
1456
1457 for (size_t k = 0; k < right(j).size(); ++k)
1458 if (k != right_key_col)
1459 new_row.append(right(j)(k));
1460
1461 result.append(std::move(new_row));
1462 }
1463 }
1464 }
1465
1466 return result;
1467}
1468
1478 const Array<Array<std::string>> & rows,
1479 size_t col_index)
1480{
1483
1484 for (size_t k = 0; k < keys.size(); ++k)
1485 {
1487 for (size_t i = 0; i < rows.size(); ++i)
1488 if (col_index < rows(i).size() and rows(i)(col_index) == keys(k))
1489 group.append(rows(i));
1490 result.append(std::move(group));
1491 }
1492
1493 return result;
1494}
1495
1515template <typename Func>
1517 const Array<Array<std::string>> & rows,
1518 Func func)
1519{
1521
1522 for (size_t i = 0; i < rows.size(); ++i)
1523 {
1524 Array<std::string> new_row;
1525 for (size_t j = 0; j < rows(i).size(); ++j)
1526 new_row.append(rows(i)(j));
1527 new_row.append(func(rows(i)));
1528 result.append(std::move(new_row));
1529 }
1530
1531 return result;
1532}
1533
1544 const Array<Array<std::string>> & rows,
1545 const std::string & old_name,
1546 const std::string & new_name)
1547{
1548 if (rows.size() == 0)
1549 return rows;
1550
1552
1553 // Process header
1554 Array<std::string> new_header;
1555 for (size_t j = 0; j < rows(0).size(); ++j)
1556 {
1557 if (rows(0)(j) == old_name)
1558 new_header.append(new_name);
1559 else
1560 new_header.append(rows(0)(j));
1561 }
1562 result.append(std::move(new_header));
1563
1564 // Copy remaining rows
1565 for (size_t i = 1; i < rows.size(); ++i)
1566 result.append(rows(i));
1567
1568 return result;
1569}
1570
1571} // namespace Aleph
1572
1573// Global namespace compatibility: export commonly used functions and classes
1574using Aleph::CsvRow;
1575using Aleph::CsvReader;
1579using Aleph::csv_escape;
1587using Aleph::csv_filter;
1601using Aleph::csv_unique;
1612
1613#endif // PARSE_CSV_H
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
size_t row
Definition ca-c-api.h:115
size_t * rows
Definition ca-c-api.h:112
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
void swap(Array &s) noexcept
Swap this with s
Definition tpl_array.H:313
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
const Array< std::string > & operator*() const
Definition parse-csv.H:861
bool operator!=(const Iterator &other) const
Definition parse-csv.H:872
Array< std::string > current_
Definition parse-csv.H:848
Iterator(CsvReader *reader, bool at_end)
Definition parse-csv.H:852
Lazy CSV reader for large files.
Definition parse-csv.H:712
void skip(size_t n)
Skip N rows.
Definition parse-csv.H:825
CsvRow next_row()
Read the next row with header access.
Definition parse-csv.H:806
Array< std::string > next()
Read the next row as Array.
Definition parse-csv.H:799
CsvReader(std::istream &stream, char delimiter=',')
Construct reader from stream.
Definition parse-csv.H:733
CsvReader(const std::string &filename, char delimiter=',')
Construct reader from file path.
Definition parse-csv.H:724
void reset()
Reset to beginning (only works for file-based readers).
Definition parse-csv.H:832
const Array< std::string > & header() const
Get the header (if read).
Definition parse-csv.H:819
CsvReader(CsvReader &&other)
Take the stream and the header of another reader, which is left reading nothing.
Definition parse-csv.H:746
Iterator end()
Definition parse-csv.H:879
Array< std::string > read_header()
Read and store the header row.
Definition parse-csv.H:785
Array< std::string > header_
Definition parse-csv.H:717
size_t rows_read() const
Get number of rows read so far.
Definition parse-csv.H:816
std::istream * stream_
Definition parse-csv.H:714
void swap(CsvReader &other)
Exchange the streams, the headers and the counters of this reader and another.
Definition parse-csv.H:768
std::ifstream file_
Definition parse-csv.H:713
bool has_next() const
Check if more rows are available.
Definition parse-csv.H:793
Iterator begin()
Definition parse-csv.H:878
CsvReader & operator=(CsvReader &&other)
Exchange this reader with another, which is left with the previous stream and header of this one.
Definition parse-csv.H:758
bool has_header() const
Check if header was read.
Definition parse-csv.H:822
A CSV row with header-based field access.
Definition parse-csv.H:602
T get(const std::string &column_name) const
Get field as numeric type by column name.
Definition parse-csv.H:663
T get(size_t index) const
Get field as numeric type.
Definition parse-csv.H:656
const Array< std::string > * header_
Definition parse-csv.H:604
const std::string & at(size_t index) const
Get field by index with bounds checking.
Definition parse-csv.H:637
const Array< std::string > * header() const
Get column names (if header set).
Definition parse-csv.H:678
const std::string & operator[](const std::string &column_name) const
Get field by column name.
Definition parse-csv.H:624
bool empty() const
Check if row is empty.
Definition parse-csv.H:672
size_t size() const
Get number of fields.
Definition parse-csv.H:669
Array< std::string > fields_
Definition parse-csv.H:603
CsvRow(Array< std::string > fields)
Construct from fields only (no header access).
Definition parse-csv.H:608
bool has_column(const std::string &column_name) const
Check if column exists.
Definition parse-csv.H:645
CsvRow(Array< std::string > fields, const Array< std::string > &header)
Construct with header reference for name-based access.
Definition parse-csv.H:612
const std::string & operator[](size_t index) const
Get field by index.
Definition parse-csv.H:616
const Array< std::string > & fields() const
Get underlying array.
Definition parse-csv.H:675
Main namespace for Aleph-w library functions.
long csv_to_number< long >(const std::string &field)
Definition parse-csv.H:556
size_t csv_find_row(const Array< Array< std::string > > &rows, Pred predicate)
Find first row matching a predicate.
Definition parse-csv.H:1057
Array< Array< std::string > > csv_sort_by_column_numeric(const Array< Array< std::string > > &rows, size_t col_index, bool ascending=true)
Sort CSV data by a column with numeric comparison.
Definition parse-csv.H:1190
Array< Array< std::string > > csv_trim_fields(const Array< Array< std::string > > &rows)
Trim whitespace from all fields.
Definition parse-csv.H:1326
std::string csv_escape(const std::string &field, char delimiter=',')
Escape a string for CSV output.
Definition parse-csv.H:321
Array< Array< std::string > > csv_read_file(const std::string &filename, char delimiter=',')
Read all rows from a CSV file.
Definition parse-csv.H:291
Array< Array< std::string > > csv_transform(const Array< Array< std::string > > &rows, Func func)
Apply a transformation to each field.
Definition parse-csv.H:1266
Array< Array< std::string > > csv_filter_by_value(const Array< Array< std::string > > &rows, size_t col_index, const std::string &value)
Filter CSV rows by column value.
Definition parse-csv.H:927
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
bool csv_skip_bom(std::istream &in)
Skip UTF-8 BOM if present.
Definition parse-csv.H:1298
Array< Array< std::string > > csv_transpose(const Array< Array< std::string > > &rows)
Transpose CSV data (swap rows and columns).
Definition parse-csv.H:1114
T csv_to_number(const std::string &field)
Convert a CSV field to a numeric type.
Definition parse-csv.H:535
Array< Array< std::string > > csv_rename_column(const Array< Array< std::string > > &rows, const std::string &old_name, const std::string &new_name)
Rename a column (in the header row).
Definition parse-csv.H:1543
Array< Array< std::string > > csv_take_rows(const Array< Array< std::string > > &rows, size_t n)
Take only the first N rows of CSV data.
Definition parse-csv.H:1002
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
Array< std::string > csv_get_column(const Array< Array< std::string > > &rows, size_t col_index)
Get a column from CSV data.
Definition parse-csv.H:498
Array< Array< std::string > > csv_join_horizontal(const Array< Array< std::string > > &left, const Array< Array< std::string > > &right)
Join two CSV datasets horizontally (add columns).
Definition parse-csv.H:1372
Array< Array< std::string > > csv_unique(const Array< Array< std::string > > &rows)
Remove duplicate rows.
Definition parse-csv.H:1230
Array< Array< Array< std::string > > > csv_group_by(const Array< Array< std::string > > &rows, size_t col_index)
Group rows by a column value.
Definition parse-csv.H:1477
float csv_to_number< float >(const std::string &field)
Definition parse-csv.H:570
and
Check uniqueness with explicit hash + equality functors.
void csv_write_row(std::ostream &out, const Array< std::string > &row, char delimiter=',', const std::string &line_ending="\n")
Write a CSV row to an output stream.
Definition parse-csv.H:377
size_t csv_num_columns(const Array< std::string > &row)
Get the number of columns in a CSV row.
Definition parse-csv.H:445
size_t csv_count_empty(const Array< Array< std::string > > &rows)
Count empty fields in CSV data.
Definition parse-csv.H:1028
std::string trim(const std::string &s)
Return a trimmed copy of a std::string (leading + trailing whitespace removed).
Array< std::string > csv_read_row(std::istream &in, char delimiter=',')
Read a single CSV row from an input stream.
Definition parse-csv.H:159
size_t csv_find_by_value(const Array< Array< std::string > > &rows, size_t col_index, const std::string &value)
Find row where column equals value.
Definition parse-csv.H:1070
bool csv_is_rectangular(const Array< Array< std::string > > &rows)
Check if all rows have the same number of columns.
Definition parse-csv.H:467
bool equal(Itor1 beg, const Itor1 &end, Itor2 cmpBeg, BinaryPredicate op=BinaryPredicate())
Test if two ranges are equal.
Definition ahAlgo.H:482
Array< std::string > csv_distinct(const Array< Array< std::string > > &rows, size_t col_index)
Get distinct values in a column.
Definition parse-csv.H:1083
Array< Array< std::string > > csv_filter(const Array< Array< std::string > > &rows, Pred predicate)
Filter CSV rows by a predicate.
Definition parse-csv.H:906
Array< Array< std::string > > csv_read_all(std::istream &in, char delimiter=',')
Read all rows from a CSV input stream.
Definition parse-csv.H:254
int csv_to_number< int >(const std::string &field)
Definition parse-csv.H:549
double csv_to_number< double >(const std::string &field)
Definition parse-csv.H:563
Array< Array< std::string > > csv_inner_join(const Array< Array< std::string > > &left, size_t left_key_col, const Array< Array< std::string > > &right, size_t right_key_col)
Inner join two CSV datasets by a key column.
Definition parse-csv.H:1432
void csv_write_file(const std::string &filename, const Array< Array< std::string > > &rows, char delimiter=',', const std::string &line_ending="\n")
Write CSV data to a file.
Definition parse-csv.H:425
Array< Array< std::string > > csv_skip_rows(const Array< Array< std::string > > &rows, size_t n)
Skip the first N rows of CSV data.
Definition parse-csv.H:984
Array< Array< std::string > > csv_select_columns(const Array< Array< std::string > > &rows, const Array< size_t > &col_indices)
Select specific columns from CSV data.
Definition parse-csv.H:953
Array< Array< std::string > > csv_fill_empty(const Array< Array< std::string > > &rows, const std::string &default_value)
Replace empty fields with a default value.
Definition parse-csv.H:1352
size_t csv_count_if(const Array< Array< std::string > > &rows, Pred predicate)
Count rows matching a predicate.
Definition parse-csv.H:1042
Array< Array< std::string > > csv_join_vertical(const Array< Array< std::string > > &top, const Array< Array< std::string > > &bottom)
Join two CSV datasets vertically (add rows).
Definition parse-csv.H:1407
Array< Array< std::string > > csv_add_column(const Array< Array< std::string > > &rows, Func func)
Add a new column with computed values.
Definition parse-csv.H:1516
Array< Array< std::string > > csv_sort_by_column(const Array< Array< std::string > > &rows, size_t col_index, bool ascending=true)
Sort CSV data by a column.
Definition parse-csv.H:1147
void csv_write_all(std::ostream &out, const Array< Array< std::string > > &rows, char delimiter=',', const std::string &line_ending="\n")
Write multiple CSV rows to an output stream.
Definition parse-csv.H:403
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
size_t csv_count_rows(const Array< Array< std::string > > &rows)
Count total number of rows.
Definition parse-csv.H:1020
STL namespace.
int keys[]
static int * k
Dynamic array container with automatic resizing.
ofstream file
Definition writeRb.C:51