如何在RDFLib中向图形添加注释或标签?
我想把数据集的名字加到图表对象里,然后再把它们取出来。我觉得应该有简单的方法可以做到这一点,但到现在为止我还没找到...谢谢!
1 个回答
3
我觉得你想要做的是给一个图形附加上下文。就像是在图形中解析出子图,每个子图都有一个名字——在使用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