我听说过许多关于OpenFST的好东西,但我很难让它发挥作用。我正在构建一个FST自动机(fst编译程序),我希望使用它作为接受器来检查一组字符串是否匹配(非常相似的正则表达式,但具有OpenFST提供的自动化优化所提供的优势)。事情是这样的:
如何检查生成的自动机是否接受字符串?
我发现了建议,输入字符串将转换为一个简单的自动机,并与接受的自动机组合以获得结果。我发现它非常笨重和奇怪。有没有更简单的方法(通过cmd行或Python/C++)?
发布于 2019-01-07 01:17:13
下面是一个关于如何测试自动机是否使用打开FST的Python包装器接受字符串的快速示例。实际上,您必须将您的输入转换为自动机,而Open甚至没有为您创建这个“线性链自动机”!幸运的是,自动化这个过程很简单,如下所示:
def linear_fst(elements, automata_op, keep_isymbols=True, **kwargs):
"""Produce a linear automata."""
compiler = fst.Compiler(isymbols=automata_op.input_symbols().copy(),
acceptor=keep_isymbols,
keep_isymbols=keep_isymbols,
**kwargs)
for i, el in enumerate(elements):
print >> compiler, "{} {} {}".format(i, i+1, el)
print >> compiler, str(i+1)
return compiler.compile()
def apply_fst(elements, automata_op, is_project=True, **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.
is_project (bool, optional): whether to keep only the output labels.
kwargs:
Additional arguments to the compiler of the linear automata .
"""
linear_automata = linear_fst(elements, automata_op, **kwargs)
out = fst.compose(linear_automata, automata_op)
if is_project:
out.project(project_output=True)
return out
def accepted(output_apply):
"""Given the output of `apply_fst` for acceptor, return True is sting was accepted."""
return output_apply.num_states() != 0让我们定义一个只接受一系列“ab”的简单受体:
f_ST = fst.SymbolTable()
f_ST.add_symbol("<eps>", 0)
f_ST.add_symbol("a", 1)
f_ST.add_symbol("b", 2)
compiler = fst.Compiler(isymbols=f_ST, osymbols=f_ST, keep_isymbols=True, keep_osymbols=True, acceptor=True)
print >> compiler, "0 1 a"
print >> compiler, "1 2 b"
print >> compiler, "2 0 <eps>"
print >> compiler, "2"
fsa_abs = compiler.compile()
fsa_abs

现在,我们可以简单地使用以下方法应用受体:
accepted(apply_fst(list("abab"), fsa_abs))
# True
accepted(apply_fst(list("ba"), fsa_abs))
# False要了解如何使用换能器,请看我的其他答案
https://stackoverflow.com/questions/45213112
复制相似问题