1 // See www.openfst.org for extensive documentation on this weighted
2 // finite-state transducer library.
4 // Definition of ReadLabelTriples based on ReadLabelPairs, like that in
5 // nlp/fst/lib/util.h for pairs, and similarly for WriteLabelTriples.
7 #ifndef FST_EXTENSIONS_MPDT_READ_WRITE_UTILS_H_
8 #define FST_EXTENSIONS_MPDT_READ_WRITE_UTILS_H_
15 #include <fst/test-properties.h>
19 // Returns true on success.
20 template <typename Label>
21 bool ReadLabelTriples(const string &filename,
22 std::vector<std::pair<Label, Label>> *pairs,
23 std::vector<Label> *assignments,
24 bool allow_negative = false) {
25 std::ifstream fstrm(filename);
27 LOG(ERROR) << "ReadIntTriples: Can't open file: " << filename;
30 static constexpr auto kLineLen = 8096;
34 while (fstrm.getline(line, kLineLen)) {
36 std::vector<char *> col;
37 SplitToVector(line, "\n\t ", &col, true);
38 // Empty line or comment?
39 if (col.empty() || col[0][0] == '\0' || col[0][0] == '#') continue;
40 if (col.size() != 3) {
41 LOG(ERROR) << "ReadLabelTriples: Bad number of columns, "
42 << "file = " << filename << ", line = " << nline;
46 const Label i1 = StrToInt64(col[0], filename, nline, allow_negative, &err);
47 if (err) return false;
48 const Label i2 = StrToInt64(col[1], filename, nline, allow_negative, &err);
49 if (err) return false;
51 const Level i3 = StrToInt64(col[2], filename, nline, allow_negative, &err);
52 if (err) return false;
53 pairs->push_back(std::make_pair(i1, i2));
54 assignments->push_back(i3);
59 // Returns true on success.
60 template <typename Label>
61 bool WriteLabelTriples(const string &filename,
62 const std::vector<std::pair<Label, Label>> &pairs,
63 const std::vector<Label> &assignments) {
64 if (pairs.size() != assignments.size()) {
65 LOG(ERROR) << "WriteLabelTriples: Pairs and assignments of different sizes";
68 std::ofstream fstrm(filename);
70 LOG(ERROR) << "WriteLabelTriples: Can't open file: " << filename;
73 for (size_t n = 0; n < pairs.size(); ++n)
74 fstrm << pairs[n].first << "\t" << pairs[n].second << "\t" << assignments[n]
77 LOG(ERROR) << "WriteLabelTriples: Write failed: "
78 << (filename.empty() ? "standard output" : filename);
86 #endif // FST_EXTENSIONS_MPDT_READ_WRITE_UTILS_H_