Iterating FSTs

In this tutorial, we demonstrate how to iterate the states and arcs of an FST.

We use the binary.fst generated in Creating FSTs using constructors and mutators as an example.

quick-start.svg

Fig. 3 binary.fst from Creating FSTs using constructors and mutators.

We will change it to the following FST:

quick-start-3.svg

Fig. 4 FST generated by this section by changing binary.fst. Note that we change the weight of each arc.

Listing 3 Iterating an FST
 1#!/usr/bin/env python3
 2
 3import graphviz
 4
 5import kaldifst
 6
 7
 8def main():
 9    fst = kaldifst.StdVectorFst.read("binary.fst")
10    for state in kaldifst.StateIterator(fst):
11        for arc in kaldifst.ArcIterator(fst, state):
12
13            # Note: We can change the attribute of the arc if we want
14            if arc.weight == 0.5:
15                arc.weight = 0.6
16            elif arc.weight == 1.5:
17                arc.weight = 1.8
18            elif arc.weight == 2.5:
19                arc.weight = 1.25
20
21            print(state, arc)
22
23    fst_dot = kaldifst.draw(fst, acceptor=False, portrait=True)
24    source = graphviz.Source(fst_dot)
25    source.render(outfile="quick-start-3.svg")
26
27
28if __name__ == "__main__":
29    main()
30"""
31Output of this file:
32
330 (ilabel: 1, olabel: 1, weight: 0.6, nextstate: 1)
340 (ilabel: 2, olabel: 2, weight: 1.8, nextstate: 1)
351 (ilabel: 3, olabel: 3, weight: 1.25, nextstate: 2)
36"""