6

我听说过很多关于 OpenFST 的好消息,但我很难让它发挥作用。我正在构建一个 FST 自动机(fstcompile),我想将其用作接受器来检查一组字符串是否匹配(非常类似于正则表达式,但具有 OpenFST 提供的自动机优化所提供的优势)。事情是这样的:
如何检查生成的自动机是否接受字符串?

我发现了一个建议,将输入字符串变成一个简单的自动机并与接受自动机组合以获得结果。我发现它非常麻烦和奇怪。有没有更简单的方法(通过 cmd 行或 Python/C++)?

4

1 回答 1

2

这是一个关于如何使用Open FST 的 Python wrapper测试自动机是否接受字符串的快速示例。事实上,你必须将你的输入变成一个自动机,而 Open FST 甚至不会为你创建这个“线性链自动机”!幸运的是,自动化这个过程很简单,如下所示:

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

在此处输入图像描述

现在我们可以使用以下方法简单地应用 Acceptor:

accepted(apply_fst(list("abab"), fsa_abs))
# True
accepted(apply_fst(list("ba"), fsa_abs))
# False

要了解如何使用传感器,请查看我的其他答案

于 2019-01-07T01:17:13.160 回答