3
我試圖將數據集的名稱添加到圖形對象,並稍後檢索它們,很確定必須有簡單的方法來完成它,但到目前爲止找不到任何東西......謝謝如何添加評論或標籤到RDFLib中的圖表?
我試圖將數據集的名稱添加到圖形對象,並稍後檢索它們,很確定必須有簡單的方法來完成它,但到目前爲止找不到任何東西......謝謝如何添加評論或標籤到RDFLib中的圖表?
我認爲是什麼你正在尋找的是將一個上下文附加到圖上。這就像創建一個圖表解析其中的子圖一樣,每個子圖都有一個名字 - 在rdflib的情況下爲URIRef
。
想象一下,你必須通過下面的兩個文件中顯示圖表:
dataA.nt
<http://data.org/inst1> <http://xmlns.com/foaf/0.1/name> "david" .
<http://data.org/inst2> <http://xmlns.com/foaf/0.1/name> "luis" .
<http://data.org/inst3> <http://xmlns.com/foaf/0.1/name> "max" .
dataB.nt
<http://data.org/inst1> <http://xmlns.com/foaf/0.1/knows> <http://data.org/inst2> .
<http://data.org/inst2> <http://xmlns.com/foaf/0.1/knows> <http://data.org/inst3> .
<http://data.org/inst3> <http://xmlns.com/foaf/0.1/knows> <http://data.org/inst1> .
而下面的一段代碼:
import rdflib
g = rdflib.ConjunctiveGraph("IOMemory",)
#g is made of two sub-graphs or triples gathered in two different contexts.
#the second paramaters identifies the URIRef for each subgraph.
g.parse("dataA.nt",rdflib.URIRef("http://mygraphs.org/names"),format="n3")
g.parse("dataB.nt",rdflib.URIRef("http://mygraphs.org/relations"),format="n3")
print "traverse all contexts and all triples for each context"
for subgraph in g.contexts():
print "Graph name",subgraph.identifier
for triple in subgraph.triples((None,None,None)):
print triple
print "traverse all contexts where a triple appears"
for subgraph in g.contexts(triple=(rdflib.URIRef('http://data.org/inst1'),rdflib.URIRef("http://xmlns.com/foaf/0.1/name"),rdflib.Literal(u'david'))):
print "Graph name",subgraph.identifier
for triple in subgraph.triples((None,None,None)):
print triple
print "traverse a triple pattern regardless the context is in"
for t in g.triples((None,rdflib.URIRef("http://xmlns.com/foaf/0.1/name"),None)):
print t