本文整理匯總了Python中rdflib.Graph.ConjunctiveGraph類的典型用法代碼示例。如果您正苦於以下問題:Python ConjunctiveGraph類的具體用法?Python ConjunctiveGraph怎麽用?Python ConjunctiveGraph使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了ConjunctiveGraph類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
def __init__(self, path=None):
self.__dict__ = self.__shared_state
if (self.data == None):
if (path == None):
raise ValueError("djubby's configuration MUST be initialized a first time, read http://code.google.com/p/djubby/wiki/GettingStarted")
else:
self.path = os.path.abspath(path)
logging.debug("Reading djubby's configuration from %s..." % self.path)
if (not os.path.exists(self.path)):
raise ValueError("Not found a proper file at '%s' with a configuration for djubby. Please, provide a right path" % self.path)
data = ConjunctiveGraph()
data.bind("conf", ns.config)
try:
data.load(path, format='n3')
except Exception, e:
raise ValueError("Not found a proper N3 file at '%s' with a configuration for djubby. Please, provide a valid N3 file" % self.path)
self.data = data
try:
self.graph = self.get_value("sparqlDefaultGraph")
self.endpoint = self.get_value("sparqlEndpoint")
except Exception, e:
raise ValueError("Not found the graph not the endpoint that it's supposed djubby have to query. Please, provide a right donfiguration")
logging.info("Using <%s> as default graph to query the endpoint <%s>" % (self.graph, self.endpoint))
self.__class__.__dict__['_Configuration__shared_state']["data"] = data #FIXME
示例2: getGraph
def getGraph():
"""
get the main graph, including data from trains.n3 on disk
"""
graph = ConjunctiveGraph()
graph.parse("trains.n3", format="n3", publicID=TT['disk#context'])
return graph
示例3: readGraphs
def readGraphs():
g = ConjunctiveGraph()
# this file should only be reread when it changes
g.parse("../config.n3", format="n3")
dl = []
startTime = time.time()
for uri in [
"http://bang:9055/graph",
"http://bang:9069/graph",
"http://bang:9070/graph",
"http://bang:9072/bang-9002/processStatus",
"http://bang:9072/bang/processStatus",
"http://bang:9072/dash/processStatus",
"http://bang:9072/slash-11000/processStatus",
"http://bang:9072/slash/processStatus",
"http://bang:9072/star/processStatus",
"http://bang:9075/graph",
]:
# this ought to not reparse the ones that are 304 not modified
d = getPage(uri)
def done(trig, uri):
g.addN(parseTrig(trig))
print "%s done in %.02fms" % (uri, 1000 * (time.time() - startTime))
d.addCallback(done, uri)
dl.append(d)
return defer.DeferredList(dl).addCallback(lambda result: g)
示例4: parse
def parse(self, result):
"""
Parse query result
@param result: text result
@return: rdf graph
"""
graph = ConjunctiveGraph()
graph.parse(StringInputSource(result))
return graph
示例5: testDefaultGraph
def testDefaultGraph():
memStore = plugin.get('IOMemory',Store)()
graph1 = Graph(memStore,URIRef("graph1"))
graph2 = Graph(memStore,URIRef("graph2"))
graph3 = Graph(memStore,URIRef("graph3"))
for n3Str,graph in [(testGraph1N3,graph1),
(testGraph2N3,graph2),
(testGraph3N3,graph3)]:
graph.parse(StringIO(n3Str),format='n3')
G = ConjunctiveGraph(memStore)
#test that CG includes triples from all 3
assert G.query(sparqlQ3),"CG as default graph should *all* triples"
assert not graph2.query(sparqlQ3),"Graph as default graph should *not* include triples from other graphs"
示例6: testQueryingMore
def testQueryingMore(self):
for result in self.results:
uri = result[0]
g = ConjunctiveGraph()
g.parse(uri)
query = Parse("""
SELECT ?person
WHERE {
<%s> foaf:primaryTopic ?person .
?person rdf:type foaf:Person .
}
""" % uri )
queryResults = g.query(query, initNs=NSbindings).serialize('python')
if (len(queryResults)>0):
self.assertEquals(str(queryResults[0]), "http://www.wikier.org/foaf#wikier")
示例7: TestSPARQLToldBNodes
class TestSPARQLToldBNodes(unittest.TestCase):
def setUp(self):
NS = u"http://example.org/"
self.graph = ConjunctiveGraph()
self.graph.parse(StringInputSource("""
@prefix : <http://example.org/> .
@prefix rdf: <%s> .
@prefix rdfs: <%s> .
[ :prop :val ].
[ a rdfs:Class ]."""%(RDF.RDFNS,RDFS.RDFSNS)), format="n3")
def testToldBNode(self):
for s,p,o in self.graph.triples((None,RDF.type,None)):
pass
query = """SELECT ?obj WHERE { %s ?prop ?obj }"""%s.n3()
print query
rt = self.graph.query(query)
self.failUnless(len(rt) == 1,"BGP should only match the 'told' BNode by name (result set size: %s)"%len(rt))
示例8: setUp
def setUp(self):
NS = u"http://example.org/"
self.graph = ConjunctiveGraph()
self.graph.parse(StringInputSource("""
@prefix : <http://example.org/> .
@prefix rdf: <%s> .
@prefix rdfs: <%s> .
[ :prop :val ].
[ a rdfs:Class ]."""%(RDF.RDFNS,RDFS.RDFSNS)), format="n3")
示例9: testSPARQLNotEquals
def testSPARQLNotEquals():
NS = u"http://example.org/"
graph = ConjunctiveGraph()
graph.parse(StringInputSource("""
@prefix : <http://example.org/> .
@prefix rdf: <%s> .
:foo rdf:value 1.
:bar rdf:value 2."""%RDF.RDFNS), format="n3")
rt = graph.query("""SELECT ?node
WHERE {
?node rdf:value ?val.
FILTER (?val != 1)
}""",
initNs={'rdf':RDF.RDFNS},
DEBUG=False)
for row in rt:
item = row[0]
assert item == URIRef("http://example.org/bar")
示例10: parse
def parse(self, source, graph):
# we're currently being handed a Graph, not a ConjunctiveGraph
assert graph.store.context_aware # is this implied by formula_aware
assert graph.store.formula_aware
conj_graph = ConjunctiveGraph(store=graph.store)
conj_graph.default_context = graph # TODO: CG __init__ should have a default_context arg
# TODO: update N3Processor so that it can use conj_graph as the sink
sink = Sink(conj_graph)
if False:
sink.quantify = lambda *args: True
sink.flatten = lambda *args: True
baseURI = graph.absolutize(source.getPublicId() or source.getSystemId() or "")
p = N3Processor("nowhere", sink, baseURI=baseURI) # pass in "nowhere" so we can set data instead
p.userkeys = True # bah
p.data = source.getByteStream().read() # TODO getCharacterStream?
p.parse()
for prefix, namespace in p.bindings.items():
conj_graph.bind(prefix, namespace)
示例11: getRdfXml
def getRdfXml(rdf):
n3 = ""
# Append the RDF namespace and print the prefix namespace mappings
rdf['namespaces']['xh1'] = "http://www.w3.org/1999/xhtml/vocab#"
rdf['namespaces']['rdf'] = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
for prefix, uri in rdf['namespaces'].items():
n3 += "@prefix %s: <%s> .\n" % (prefix, uri)
# Print each subject-based triple to the screen
triples = rdf['triples']
processed = []
# Get all of the non-bnode subjects
nonBnodeSubjects = getNonBnodeSubjects(triples)
# Get all of the bnode subjects
bnodeSubjects = getBnodeSubjects(triples)
for subject in nonBnodeSubjects:
subjectTriples = getTriplesBySubject(subject, triples)
#print "PROCESSING NB SUBJECT:", subjectTriples
if(subject not in processed):
n3 += tripleToN3(subjectTriples, processed, triples)
processed.append(subject)
for subject in bnodeSubjects:
subjectTriples = getTriplesBySubject(subject, triples)
#print "PROCESSING BN SUBJECT:", subject
if(subject not in processed):
n3 += bnodeToN3(subjectTriples, processed, triples)
n3 += " .\n"
#print n3
g = ConjunctiveGraph()
g.parse(StringIO(n3), format="n3")
rdfxml = g.serialize()
return rdfxml
示例12: testAggregateSPARQL
def testAggregateSPARQL():
memStore = plugin.get('IOMemory',Store)()
graph1 = Graph(memStore,URIRef("graph1"))
graph2 = Graph(memStore,URIRef("graph2"))
graph3 = Graph(memStore,URIRef("graph3"))
for n3Str,graph in [(testGraph1N3,graph1),
(testGraph2N3,graph2),
(testGraph3N3,graph3)]:
graph.parse(StringIO(n3Str),format='n3')
graph4 = Graph(memStore,RDFS.RDFSNS)
graph4.parse(RDFS.RDFSNS)
G = ConjunctiveGraph(memStore)
rt = G.query(sparqlQ)
assert len(rt) > 1
#print rt.serialize(format='xml')
LOG_NS = Namespace(u'http://www.w3.org/2000/10/swap/log#')
rt=G.query(sparqlQ2,initBindings={u'?graph' : URIRef("graph3")})
#print rt.serialize(format='json')
assert rt.serialize('python')[0] == LOG_NS.N3Document,str(rt)
示例13: main
def main():
"""Main Function
Simple command-line procedure for web2rdf."""
if len(sys.argv) != 2:
print "Must call with a URI parameter."
print "Usage: %s uriSrc" % sys.argv[0]
return
uri = sys.argv[1]
# Get the RDF
wrdf = Web2Rdf(uri)
rdf = wrdf.getRdf()
if not rdf:
print "No RDF returned!"
return False
print "Got RDF..."
rdf = rdfString(rdf)
# Open Storage
print "Opening store..."
db = "./testdb.sqlite"
rstore = RdfStore('sqlite', db)
rstore.open()
print "Storing..."
graph = Graph(rstore.get(), identifier = URIRef("http://slashdot/Test2"))
#graph.parse("example.rdf")
graph.parse(rdf, publicID=uri)
graph.commit()
示例14: to_rdf
def to_rdf(self, format="settings"):
"""Convert the RdfSerializer store into RDF."""
graph = Graph()
for k, v in self.NAMESPACES.iteritems():
graph.bind(k, v)
for g in self.subgraphs:
graph += g
if format == "settings":
format = settings.RDF_SERIALIZATION
return graph.serialize(format=format)
示例15: RdfParser
class RdfParser(object):
"""A basic wrapper for RdfLib's RDF parser.
This class aims to accomplish easier parsing, extraction of Models,
etc."""
def __init__(self, rdf, format='guess'):
"""Init the parser with the graph string."""
self.graph = Graph()
if format == 'guess':
format = self.__guess_format(rdf)
print 'RdfParser guesses format to be: %s' % format
try:
self.graph.load(StringIO(rdf), format=format)
except:
print "Failed to parse RDF:"
print rdf[0:100]
def extract(self, datatype):
"""Extract all of the data of a given datatype."""
data = []
ns = RdfSerializer.NAMESPACES['sylph'] # TODO: Awkward.
for sub in self.graph.subjects(RDF.type, ns[datatype]):
idx = str(sub)
item = {'uri': idx}
for pred, obj in self.graph.predicate_objects(sub):
if pred == RDF.type:
continue
if obj == ns['None']:
obj = None
elif type(obj) == URIRef:
obj = unicode(obj)
elif type(obj) == Literal:
obj = obj.toPython()
if type(obj) == Literal: # Don't be silly, RdfLib!
obj = unicode(obj)
predstr = str(pred).rpartition('#')[2].rpartition('/')[2]
item[predstr] = obj
data.append(item)
return data
@staticmethod
def __guess_format(st):
"""Guess the format of the input string."""
# TODO: At present, it can only guess between XML and n3, even
# then this is a vague heuristic.
if st.startswith('<'):
return 'xml'
return 'n3'