更新 Yann Dubois 对 python3 的回答:
import pywrapfst as fst
print("")
f_ST: fst.SymbolTable
def linear_fst(elements, automata_op, keep_isymbols=True, **kwargs):
"""Produce a linear automata."""
compiler = fst.Compiler(
isymbols=f_ST, # There should be some way to get this from automata_op
acceptor=keep_isymbols,
keep_isymbols=keep_isymbols,
**kwargs
)
for i, el in enumerate(elements):
print("{} {} {}".format(i, i + 1, el), end="", file=compiler)
print(str(i + 1), end="", file=compiler)
lf = compiler.compile()
return lf
def apply_fst(elements, automata_op, print_la=True, is_project=False, **kwargs):
"""Compose a linear automata generated from `elements` with `automata_op`.
Args:
elements (list): ordered list of edge symbols for a linear automata.
automata_op (Fst): automata that will be applied.
print_la (bool, optional): print linear automata as text representation
is_project (str, optional): whether to keep only the "input" or "output" labels.
kwargs: Additional arguments to the compiler of the linear automata .
"""
linear_automata = linear_fst(elements, automata_op, **kwargs)
if print_la:
print("Linear Automata:\n", linear_automata)
out = fst.compose(linear_automata, automata_op)
if is_project:
out.project("output")
return out
f_ST = fst.SymbolTable()
f_ST.add_symbol("<eps>", 0)
f_ST.add_symbol("A", 1)
f_ST.add_symbol("a", 2)
f_ST.add_symbol("b", 3)
compiler = fst.Compiler(
isymbols=f_ST, osymbols=f_ST, keep_isymbols=True, keep_osymbols=True
)
print("0 0 a A", end="", file=compiler)
print("0 0 b b", end="", file=compiler)
print("0", end="", file=compiler)
caps_A = compiler.compile()
print("Uppercase Transducer with", caps_A.num_states(), "states:\n", caps_A)
caps_I = apply_fst(list("abab"), caps_A)
print("Output:\n", caps_I)
这打印:
Uppercase Transducer with 1 states:
0 0 a A
0 0 b b
0
Linear Automata:
0 1 a 2
1 2 b 3
2 3 a 2
3 4 b 3
4
Output:
0 1 a A
1 2 b b
2 3 a A
3 4 b b
4