21 #ifndef FST_EXTENSIONS_MPDT_READ_WRITE_UTILS_H_ 22 #define FST_EXTENSIONS_MPDT_READ_WRITE_UTILS_H_ 33 #include <string_view> 38 template <
typename Label>
40 std::vector<std::pair<Label, Label>> *pairs,
41 std::vector<Label> *assignments) {
42 std::ifstream fstrm(source);
44 LOG(ERROR) <<
"ReadIntTriples: Can't open file: " << source;
47 static constexpr
auto kLineLen = 8096;
51 while (fstrm.getline(line, kLineLen)) {
53 std::vector<std::string_view> col =
56 if (col.empty() || col[0].empty() || col[0][0] ==
'#')
continue;
57 if (col.size() != 3) {
58 LOG(ERROR) <<
"ReadLabelTriples: Bad number of columns, " 59 <<
"file = " << source <<
", line = " << nline;
63 const Label i1 =
StrToInt64(col[0], source, nline, &err);
64 if (err)
return false;
65 const Label i2 =
StrToInt64(col[1], source, nline, &err);
66 if (err)
return false;
68 const Level i3 =
StrToInt64(col[2], source, nline, &err);
69 if (err)
return false;
70 pairs->push_back(std::make_pair(i1, i2));
71 assignments->push_back(i3);
77 template <
typename Label>
79 const std::vector<std::pair<Label, Label>> &pairs,
80 const std::vector<Label> &assignments) {
81 if (pairs.size() != assignments.size()) {
82 LOG(ERROR) <<
"WriteLabelTriples: Pairs and assignments of different sizes";
85 std::ofstream fstrm(source);
87 LOG(ERROR) <<
"WriteLabelTriples: Can't open file: " << source;
90 for (
size_t n = 0; n < pairs.size(); ++n)
91 fstrm << pairs[n].first <<
"\t" << pairs[n].second <<
"\t" << assignments[n]
94 LOG(ERROR) <<
"WriteLabelTriples: Write failed: " 95 << (source.empty() ?
"standard output" : source);
103 #endif // FST_EXTENSIONS_MPDT_READ_WRITE_UTILS_H_
internal::StringSplitter StrSplit(std::string_view full, ByAnyChar delim)
bool ReadLabelTriples(const std::string &source, std::vector< std::pair< Label, Label >> *pairs, std::vector< Label > *assignments)
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 *error=nullptr)