21 #ifndef FST_EXTENSIONS_MPDT_READ_WRITE_UTILS_H_ 22 #define FST_EXTENSIONS_MPDT_READ_WRITE_UTILS_H_ 30 #include <string_view> 35 template <
typename Label>
37 std::vector<std::pair<Label, Label>> *pairs,
38 std::vector<Label> *assignments,
39 bool allow_negative =
false) {
40 std::ifstream fstrm(source);
42 LOG(ERROR) <<
"ReadIntTriples: Can't open file: " << source;
45 static constexpr
auto kLineLen = 8096;
49 while (fstrm.getline(line, kLineLen)) {
51 std::vector<std::string_view> col =
54 if (col.empty() || col[0].empty() || col[0][0] ==
'#')
continue;
55 if (col.size() != 3) {
56 LOG(ERROR) <<
"ReadLabelTriples: Bad number of columns, " 57 <<
"file = " << source <<
", line = " << nline;
61 const Label i1 =
StrToInt64(col[0], source, nline, allow_negative, &err);
62 if (err)
return false;
63 const Label i2 =
StrToInt64(col[1], source, nline, allow_negative, &err);
64 if (err)
return false;
66 const Level i3 =
StrToInt64(col[2], source, nline, allow_negative, &err);
67 if (err)
return false;
68 pairs->push_back(std::make_pair(i1, i2));
69 assignments->push_back(i3);
75 template <
typename Label>
77 const std::vector<std::pair<Label, Label>> &pairs,
78 const std::vector<Label> &assignments) {
79 if (pairs.size() != assignments.size()) {
80 LOG(ERROR) <<
"WriteLabelTriples: Pairs and assignments of different sizes";
83 std::ofstream fstrm(source);
85 LOG(ERROR) <<
"WriteLabelTriples: Can't open file: " << source;
88 for (
size_t n = 0; n < pairs.size(); ++n)
89 fstrm << pairs[n].first <<
"\t" << pairs[n].second <<
"\t" << assignments[n]
92 LOG(ERROR) <<
"WriteLabelTriples: Write failed: " 93 << (source.empty() ?
"standard output" : source);
101 #endif // FST_EXTENSIONS_MPDT_READ_WRITE_UTILS_H_ bool ReadLabelTriples(const std::string &source, std::vector< std::pair< Label, Label >> *pairs, std::vector< Label > *assignments, bool allow_negative=false)
internal::StringSplitter StrSplit(std::string_view full, ByAnyChar delim)
bool WriteLabelTriples(const std::string &source, const std::vector< std::pair< Label, Label >> &pairs, const std::vector< Label > &assignments)
int64_t StrToInt64(std::string_view s, std::string_view source, size_t nline, bool allow_negative, bool *error=nullptr)