1

Python で RDF データをロードすると、次のようになります。

from rdflib import Graph
g = Graph()
g.parse("demo.nt", format="nt")

しかし、フォーマット パーサーをストリーミング パーサーとしてスタンドアロンで使用し、解析されたトークンのストリームを取得するにはどうすればよいでしょうか? ヒント/コード例を教えてもらえますか?

4

1 に答える 1

3

NT パーサーは、「シンク」(シンク頂点ではない) を使用してトリプルを解析時に格納するというパラダイムに従います。デフォルトのNT パーサーは NTriplesParser を使用するため、探しているトークンは実際にはトリプルであると思います。

以下の例と同じ方法を使用して、NTSink をオーバーライドできます

この例では、テスト用の NT 形式のファイルを読み込み、 print1 行が解析されるたびに 1 行のテキストを読み込みます。行を印刷する代わりに、欠落しているメソッドを実行できます。

example.py: という名前の同じディレクトリにファイルが必要です./anons-01.nt

from rdflib.plugins.parsers.ntriples import NTriplesParser, Sink
# The NTriplesParser is what is used for a format="nt" parsing as found:
#  https://github.com/RDFLib/rdflib/blob/395a40101fe133d97f454ee61da0fc748a93b007/rdflib/plugins/parsers/nt.py#L2

# Example NT file from:
#  https://github.com/RDFLib/rdflib/blob/395a40101fe133d97f454ee61da0fc748a93b007/test/nt/anons-01.nt


class StreamSink(Sink):
    """
    A sink is used to store the results of parsing, this almost matches the sink
    example shown in ntriples:
      https://github.com/RDFLib/rdflib/blob/395a40101fe133d97f454ee61da0fc748a93b007/rdflib/plugins/parsers/ntriples.py#L43
    """
    def triple(self, s, p, o):
        self.length += 1
        print "Stream of triples s={s}, p={p}, o={o}".format(s=s, p=p, o=o)


if __name__ == "__main__":
    # Create a new parser and try to parse the example NT file.
    n = NTriplesParser(StreamSink())
    with open("./anons-01.nt", "r") as anons:
        n.parse(anons)

output:

Stream of triples s=N33bb017ce2c340999d2aa6a071d79678, p=http://example.org/#p, o=http://example.org/#q
Stream of triples s=N33bb017ce2c340999d2aa6a071d79678, p=http://example.org/#r, o=http://example.org/#s
Stream of triples s=Nb8d195e0586f42c4bcc703be897c74fa, p=http://example.org/#p, o=http://example.org/#q
Stream of triples s=Nb8d195e0586f42c4bcc703be897c74fa, p=http://example.org/#r, o=N235a8c8b4f91453892da284cb0c490e0
Stream of triples s=N235a8c8b4f91453892da284cb0c490e0, p=http://example.org/#s, o=http://example.org/#t
于 2015-03-18T19:15:41.420 に答える