本文整理汇总了Python中rdflib.graph.Graph类的典型用法代码示例。如果您正苦于以下问题:Python Graph类的具体用法?Python Graph怎么用?Python Graph使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Graph类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _new_sioc_post
def _new_sioc_post(self, topic_uri, recipient_uri):
""" Create a new rdf/xml sioc:Post based on a topic, and for a given recipient.
Timestamp is set to now, and sender is taken from WebID authenticated person (TBC). """
uri = self.message_uri_prefix + uuid.uuid1().hex
graph = Graph()
graph.add(
(rdflib.URIRef(uri),
rdflib.URIRef("http://xmlns.com/foaf/0.1/primaryTopic"),
rdflib.URIRef(topic_uri)))
graph.add(
(rdflib.URIRef(uri),
rdflib.URIRef("http://rdfs.org/sioc/ns#addressed_to"),
rdflib.URIRef(recipient_uri)))
graph.add(
(rdflib.URIRef(uri),
rdflib.URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
rdflib.URIRef(self.sioc_ns+"Post")))
graph.add(
(rdflib.URIRef(uri),
rdflib.URIRef("http://purl.org/dc/terms/created"),
rdflib.Literal(strftime("%Y-%m-%dT%H:%M:%SZ")))) # FIXME forces zulu time, which may be technically incorrect
rdf = graph.serialize(format="xml") # rdf/xml
return {"rdf": rdf, "uri": uri}
示例2: _find_graph
def _find_graph(self):
if self._is_dbpedia_uri():
return SPARQLGraph('http://dbpedia.org/sparql')
else:
graph = Graph()
graph.parse(self.uri)
return graph
示例3: testIssue29
def testIssue29(self):
input = """@prefix foo-bar: <http://example.org/> .
foo-bar:Ex foo-bar:name "Test" . """
g = Graph()
g.parse(data=input, format="n3")
示例4: harvest_collection
def harvest_collection(col_url, col_uri, store_host, manifest_file=None):
store_host = clean_store_host(store_host)
with transaction.commit_on_success():
col_g = Graph(store=rdfstore(), identifier=URIRef(col_uri))
collection.fetch_and_parse(col_url, col_g, manifest_file=manifest_file)
localize_describes(store_host, col_uri, col_url, col_g)
res_uris_urls = collection.aggregated_uris_urls(col_uri, col_g)
for res_uri, res_url in res_uris_urls:
res_g = Graph(store=rdfstore(), identifier=URIRef(res_uri))
collection.fetch_and_parse(res_url, res_g)
for pred in col_res_attributes:
for t in res_g.triples((res_uri, pred, None)):
col_g.add(t)
aggr_uris_urls = collection.aggregated_uris_urls(res_uri, res_g)
for aggr_uri, aggr_url in aggr_uris_urls:
if aggr_url:
collection.fetch_and_parse(aggr_url, res_g)
localize_describes(store_host, aggr_uri, aggr_url, res_g)
localize_describes(store_host, aggr_uri, aggr_url, col_g)
seq_uris_urls = collection.aggregated_seq_uris_urls(res_uri, res_g)
for seq_uri, seq_url in seq_uris_urls:
page_uris_urls = collection.aggregated_uris_urls(seq_uri, res_g)
for page_uri, page_url in page_uris_urls:
localize_describes(store_host, page_uri, page_url, res_g)
localize_describes(store_host, res_uri, res_url, res_g)
localize_describes(store_host, res_uri, res_url, col_g)
示例5: testGraphIntersection
def testGraphIntersection(self):
g1 = Graph()
g2 = Graph()
g1.add((self.tarek, self.likes, self.pizza))
g1.add((self.michel, self.likes, self.cheese))
g2.add((self.bob, self.likes, self.cheese))
g2.add((self.michel, self.likes, self.cheese))
g3 = g1 * g2
self.assertEquals(len(g3), 1)
self.assertEquals((self.tarek, self.likes, self.pizza) in g3, False)
self.assertEquals((self.tarek, self.likes, self.cheese) in g3, False)
self.assertEquals((self.bob, self.likes, self.cheese) in g3, False)
self.assertEquals((self.michel, self.likes, self.cheese) in g3, True)
g1 *= g2
self.assertEquals(len(g1), 1)
self.assertEquals((self.tarek, self.likes, self.pizza) in g1, False)
self.assertEquals((self.tarek, self.likes, self.cheese) in g1, False)
self.assertEquals((self.bob, self.likes, self.cheese) in g1, False)
self.assertEquals((self.michel, self.likes, self.cheese) in g1, True)
示例6: enhance
def enhance(self, content, input=Format.TEXT, output=Format.JSON):
analysis = self.status["analyses"][0]
params = {
self.param_in: input.name,
self.param_out: output.name
}
resource = self._build_url("/%s/%s/%s" % (self.path, analysis, self.enhance_path), params)
logging.debug("Making request to %s" % resource)
response = self._post(resource, content, input.mimetype, output.mimetype)
if response.status_code != 200:
logging.error("Enhance request returned %d: %s" % (response.status_code, response.reason))
return response.text
else:
contentType = from_mimetype(response.headers["Content-Type"])
if contentType == Format.JSON or contentType == Format.REDLINKJSON:
return json.loads(response.text)
elif contentType == Format.XML or contentType == Format.REDLINKXML:
return minidom.parse(response.text)
elif contentType.rdflibMapping:
g = Graph()
g.parse(data=response.text, format=contentType.rdflibMapping)
return g
else:
logging.warn("Handler not found for %s, so returning raw text response..." % contentType.mimetype)
return response.text
示例7: fromuri2
def fromuri2(self, uri):
self.uri = uri
if not uri.startswith('http://rdf.freebase.com'):
self.checkuri()
try:
g = Graph()
g.parse(self.uri)
if g:
logger.info("INFO process_rdf.py - returning graph for " + self.uri)
return g
else:
raise Exception('Nothing was returned, probably caused URL serving no RDF or bad RDF (eg. Freebase): '
'"No handlers could be found for logger "process_rdf.py" -- uri was ' + self.uri)
except URLError as e:
logger.error("URLError process_rdf.py - " + e.message)
raise Exception('URLError, cause either bad URL or no internet connection - ' + e.message + '(uri was ' + self.uri + ')')
except SAXParseException as e:
logger.error("SAXParseException process_rdf.py - " + e.message + '(uri was' + self.uri + ')')
raise Exception('SAXParseException')
except AttributeError as e:
logger.error("AttributeError process_rdf.py - " + e.message + '(uri was' + self.uri + ')')
raise Exception('AttributeError')
else:
self.fromfreebaseuri()
示例8: read_project
def read_project(request, project_uri):
"""Returns a HttpResponse of the cached project metadata graph"""
project_uri = URIRef(project_uri)
if request.user.is_authenticated():
if permissions.has_permission_over(project_uri, user=request.user, permission=NS.perm.mayRead):
identifier = uris.uri('semantic_store_projects', uri=project_uri)
store_metadata_graph = get_project_metadata_graph(project_uri)
ret_graph = Graph()
ret_graph += store_metadata_graph
add_is_described_bys(request, project_uri, ret_graph)
for permission in ProjectPermission.objects.filter(identifier=project_uri):
user = permission.user
user_uri = uris.uri('semantic_store_users', username=user.username)
perm_uri = permissions.PERMISSION_URIS_BY_MODEL_VALUE[permission.permission]
ret_graph += user_metadata_graph(user=user)
ret_graph.add((user_uri, NS.perm.hasPermissionOver, project_uri))
ret_graph.add((user_uri, perm_uri, project_uri))
if len(ret_graph) > 0:
return NegotiatedGraphResponse(request, ret_graph)
else:
return HttpResponseNotFound()
else:
return HttpResponseForbidden('User "%s" does not have read permissions over project "%s"' % (request.user.username, project_uri))
else:
return HttpResponse(status=401)
示例9: delete_triples_from_project
def delete_triples_from_project(request, uri):
"""Deletes the triples in a graph provided by a request object from the project graph.
Returns an HttpResponse of all the triples which were successfully removed from the graph."""
if request.user.is_authenticated():
if permissions.has_permission_over(uri, user=request.user, permission=NS.perm.mayUpdate):
removed = Graph()
bind_namespaces(removed)
try:
g = parse_request_into_graph(request)
except (ParserError, SyntaxError) as e:
return HttpResponse(status=400, content="Unable to parse serialization.\n%s" % e)
project_g = get_project_graph(uri)
project_metadata_g = get_project_metadata_graph(uri)
for t in g:
if t in project_g:
project_g.remove(t)
removed.add(t)
project_metadata_g.remove(t)
return NegotiatedGraphResponse(request, removed)
else:
return HttpResponseForbidden('User "%s" does not have update permissions over project "%s"' % (request.user.username, uri))
else:
return HttpResponse(status=401)
示例10: Processor
class Processor(object):
def __init__(self, stream_urls):
self.client = client.Client(stream_urls,
event_callback=self._handle_event,
error_callback=self._handle_error,
separate_events=False)
self.triple_store = Graph('Sleepycat',
'http://www.it.uc3m.es/jaf/ns/slog/db')
self.db_dir = 'dbdir'
def start(self, loop=False):
self.triple_store.open(self.db_dir)
self.client.start(loop=loop)
def stop(self):
self.triple_store.close()
self.client.stop()
def _handle_error(self, message, http_error=None):
pass
def _handle_event(self, evs):
print('Received {} events.'.format(len(evs)))
for event in evs:
self.triple_store += event.body
print(len(self.triple_store))
示例11: test_c
def test_c():
"""Test reading N3 from a codecs.StreamReader, outputting unicode"""
g = Graph()
# rdf_reader.seek(0)
g.parse(source=rdf_reader, format='n3')
v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel"))
assert v==Literal(u"C\u00f4te d'Ivoire", lang='fr')
示例12: NegationOfAtomicConcept
class NegationOfAtomicConcept(unittest.TestCase):
def setUp(self):
self.ontGraph = Graph()
self.ontGraph.bind('ex', EX_NS)
self.ontGraph.bind('owl', OWL_NS)
Individual.factoryGraph = self.ontGraph
def testAtomicNegation(self):
bar=EX.Bar
baz=~bar
baz.identifier = EX_NS.Baz
ruleStore,ruleGraph,network=SetupRuleStore(makeNetwork=True)
individual=BNode()
individual2=BNode()
(EX.OtherClass).extent = [individual]
bar.extent = [individual2]
NormalFormReduction(self.ontGraph)
self.assertEqual(repr(baz),
"Class: ex:Baz DisjointWith ex:Bar\n")
posRules,negRules=CalculateStratifiedModel(network,self.ontGraph,[EX_NS.Foo])
self.failUnless(not posRules,"There should be no rules in the 0 strata!")
self.failUnless(len(negRules)==1,"There should only be one negative rule in a higher strata")
self.assertEqual(repr(negRules[0]),
"Forall ?X ( ex:Baz(?X) :- not ex:Bar(?X) )")
baz.graph = network.inferredFacts
self.failUnless(individual in baz.extent,
"%s should be a member of ex:Baz"%individual)
self.failUnless(individual2 not in baz.extent,
"%s should *not* be a member of ex:Baz"%individual2)
示例13: NegatedDisjunctTest
class NegatedDisjunctTest(unittest.TestCase):
def setUp(self):
self.ontGraph = Graph()
self.ontGraph.bind('ex', EX_NS)
self.ontGraph.bind('owl', OWL_NS)
Individual.factoryGraph = self.ontGraph
def testStratified(self):
bar=EX.Bar
baz=EX.Baz
noBarOrBaz = ~(bar|baz)
omega = EX.Omega
foo = omega & noBarOrBaz
foo.identifier = EX_NS.Foo
ruleStore,ruleGraph,network=SetupRuleStore(makeNetwork=True)
individual=BNode()
omega.extent = [individual]
NormalFormReduction(self.ontGraph)
self.assertEqual(repr(foo),
"ex:Omega that ( not ex:Bar ) and ( not ex:Baz )")
posRules,negRules=CalculateStratifiedModel(network,self.ontGraph,[EX_NS.Foo])
foo.graph = network.inferredFacts
self.failUnless(not posRules,"There should be no rules in the 0 strata!")
self.assertEqual(repr(negRules[0]),"Forall ?X ( ex:Foo(?X) :- And( ex:Omega(?X) not ex:Bar(?X) not ex:Baz(?X) ) )")
self.failUnless(len(negRules)==1,"There should only be one negative rule in a higher strata")
self.failUnless(individual in foo.extent,
"%s should be a member of ex:Foo"%individual)
示例14: setUp
def setUp(self):
self.graph1 = Graph(store=self.store_name)
self.graph2 = Graph(store=self.store_name)
self.graph1.open(self.settings1, True)
self.graph2.open(self.settings2, True)
self.oNS = Namespace("http://www.example.org/rdf/things#")
self.sNS = Namespace("http://www.example.org/rdf/people#")
self.pNS = Namespace("http://www.example.org/rdf/relations/")
self.graph1.bind('people',self.sNS)
self.graph1.bind('relations',self.pNS)
self.graph1.bind('things',self.oNS)
self.graph2.bind('people',self.sNS)
self.graph2.bind('relations',self.pNS)
self.graph2.bind('things',self.oNS)
self.michel = self.sNS.michel
self.tarek = self.sNS.tarek
self.alice = self.sNS.alice
self.bob = self.sNS.bob
self.likes = self.pNS.likes
self.hates = self.pNS.hates
self.named = self.pNS.named
self.pizza = self.oNS.pizza
self.cheese = self.oNS.cheese
示例15: open
def open(self, configuration, create=False):
"""Raise a ModificationException if create, as this graph is read-only.
"""
if create:
raise ModificationException() #ReadOnlyGraph does not support this
else:
Graph.open(self, configuration, create)