为什么OpenFST似乎没有"运行"或"接受"或"转换"命令?

sop*_*ros 6 python openfst fst

我听说过很多关于OpenFST的好东西,但我努力让它发挥作用.我正在构建一个FST自动机(fstcompile),我想用它作为接受器来检查一组字符串是否匹配(非常相似的正则表达式,但具有OpenFST提供的自动机优化提供的优点).事情就是这样:
如何检查生成的自动机是否接受字符串?

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

Yan*_*ois 2

下面是一个关于如何使用Open FST 的 Python 包装器测试自动机是否接受字符串的简单示例。事实上,你必须将你的输入变成一个自动机,而 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
Run Code Online (Sandbox Code Playgroud)

让我们定义一个简单的 Acceptor,它只接受一系列“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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

accepted(apply_fst(list("abab"), fsa_abs))
# True
accepted(apply_fst(list("ba"), fsa_abs))
# False
Run Code Online (Sandbox Code Playgroud)

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