本文整理汇总了Python中rdflib.graph.Graph.add方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.add方法的具体用法?Python Graph.add怎么用?Python Graph.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.graph.Graph
的用法示例。
在下文中一共展示了Graph.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_to_collection
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
def add_to_collection(self, name, uri):
'''
Add a URI has a member of a collection
@param name: the name of the collection
@param uri: the uri of the resource to add as a member
'''
# Get the URI for this collection
collection_uri = self.get_uri(name)
# Create and populate the description of the membership
graph = Graph()
graph.add((URIRef(uri), DCTERMS.isPartOf, URIRef(collection_uri)))
data = graph.serialize(format="nt").decode()
# Prepare the query
query = """
INSERT DATA {
__PAYLOAD__
}
""".replace("__PAYLOAD__", data)
sparql = SPARQLWrapper(self.sparul)
sparql.setQuery(query)
sparql.setMethod(POST)
# Execute it
sparql.query()
示例2: test_16_bnode
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
def test_16_bnode(self):
g = Graph(store, identifier=TEST_GRAPH)
b = BNode()
g.add((b, RDF.type, RDFS.Resource))
# get a new graph just to be sure
g = Graph(store, identifier=TEST_GRAPH)
assert (b, RDF.type, RDFS.Resource) in g
示例3: harvest_collection
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
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)
示例4: reduce
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
def reduce(mode='object'):
# input comes from stdin
previous_key = None
graph = Graph()
# load a triples with same _key into a model
for line in sys.stdin:
line = line.strip()
current_key, triple = line.split('\t', 1)
# all lines having same key have
# been completely processed
if current_key != previous_key and previous_key != None:
if mode == 'object':
#print('gggg', graph.serialize(format='nt'))
replaceObjectUri(graph)
elif mode == 'subject':
replaceSubjectUri(graph)
# clear graph
graph = Graph()
# load triple triple into temp graph
# for easier processing
tmp_graph = Graph()
tmp_graph.parse(data=triple,
format="nt")
# get triple from temporary graph
for sub, pred, obj in tmp_graph:
# add to current graph
graph.add((sub, pred, obj))
previous_key = current_key
if mode == 'object':
#print('gggg', graph)
replaceObjectUri(graph)
elif mode == 'subject':
replaceSubjectUri(graph)
示例5: _sparql_construct
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
def _sparql_construct(self, q, cursor):
log.debug("_sparql_construct")
g = Graph()
results = cursor.execute(q.encode("utf-8"))
for result in results:
g.add(resolve(cursor, x) for x in result)
return g
示例6: delete_triples_from_project
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
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)
示例7: UniversalRestrictionTest
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
class UniversalRestrictionTest(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 testNegatedDisjunctionTest(self):
contains=Property(EX_NS.contains)
omega = EX.Omega
alpha = EX.Alpha
innerDisjunct = omega | alpha
foo = EX.foo
testClass1 = foo & (contains|only|~innerDisjunct)
testClass1.identifier = EX_NS.Bar
self.assertEqual(repr(testClass1),
"ex:foo that ( ex:contains only ( not ( ex:Omega or ex:Alpha ) ) )")
NormalFormReduction(self.ontGraph)
self.assertEqual(repr(testClass1),
"ex:foo that ( not ( ex:contains some ( ex:Omega or ex:Alpha ) ) )")
individual1 = BNode()
individual2 = BNode()
foo.extent = [individual1]
contains.extent = [(individual1,individual2)]
(EX.Baz).extent = [individual2]
ruleStore,ruleGraph,network=SetupRuleStore(makeNetwork=True)
posRules,ignored=CalculateStratifiedModel(network,self.ontGraph,[EX_NS.Bar])
self.failUnless(not posRules,"There should be no rules in the 0 strata!")
self.assertEqual(len(ignored),2,"There should be 2 'negative' rules")
testClass1.graph = network.inferredFacts
self.failUnless(individual1 in testClass1.extent,
"%s should be in ex:Bar's extent"%individual1)
def testNominalPartition(self):
partition = EnumeratedClass(EX_NS.part,
members=[EX_NS.individual1,
EX_NS.individual2,
EX_NS.individual3])
subPartition = EnumeratedClass(members=[EX_NS.individual1])
partitionProp = Property(EX_NS.propFoo,
range=partition.identifier)
self.testClass = (EX.Bar) & (partitionProp|only|subPartition)
self.testClass.identifier = EX_NS.Foo
self.assertEqual(repr(self.testClass),
"ex:Bar that ( ex:propFoo only { ex:individual1 } )")
self.assertEqual(repr(self.testClass.identifier),
"rdflib.term.URIRef('http://example.com/Foo')")
NormalFormReduction(self.ontGraph)
self.assertEqual(repr(self.testClass),
"ex:Bar that ( not ( ex:propFoo value ex:individual2 ) ) and ( not ( ex:propFoo value ex:individual3 ) )")
ruleStore,ruleGraph,network=SetupRuleStore(makeNetwork=True)
ex = BNode()
(EX.Bar).extent = [ex]
self.ontGraph.add((ex,EX_NS.propFoo,EX_NS.individual1))
CalculateStratifiedModel(network,self.ontGraph,[EX_NS.Foo])
self.failUnless((ex,RDF.type,EX_NS.Foo) in network.inferredFacts,
"Missing level 1 predicate (ex:Foo)")
示例8: read_project
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
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: testGraphAdd
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
def testGraphAdd(self):
g1=Graph()
g2=Graph()
tarek = self.tarek
michel = self.michel
bob = self.bob
likes = self.likes
hates = self.hates
pizza = self.pizza
cheese = self.cheese
g1.add((tarek, likes, pizza))
g2.add((bob, likes, cheese))
g3=g1+g2
self.assertEquals(len(g3), 2)
self.assertEquals((tarek, likes, pizza) in g3, True)
self.assertEquals((tarek, likes, cheese) in g3, False)
self.assertEquals((bob, likes, cheese) in g3, True)
g1+=g2
self.assertEquals(len(g1), 2)
self.assertEquals((tarek, likes, pizza) in g1, True)
self.assertEquals((tarek, likes, cheese) in g1, False)
self.assertEquals((bob, likes, cheese) in g1, True)
示例10: testConjunction
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
def testConjunction(self):
self.addStuffInMultipleContexts()
triple = (self.pizza, self.likes, self.pizza)
# add to context 1
graph = Graph(self.graph.store, self.c1)
graph.add(triple)
self.assertEquals(len(self.graph), len(graph))
示例11: jsondict2graph
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
def jsondict2graph(json_dict):
g = Graph()
[g.bind(*x) for x in ns_store.items()]
for triple in json_dict['results']['bindings']:
ts = triple['s'].get('type',None)
vs = triple['s']['value']
if ts == 'uri':
s = URIRef(vs)
elif ts == 'literal':
s = Literal(vs)
elif ts == 'bnode':
s = BNode(vs)
#logging.debug(s)
p = URIRef(triple['p']['value'])
#logging.debug(p)
to = triple['o'].get('type',None)
vo = triple['o']['value']
dto = triple['o'].get('datatype',None)
if to == 'uri':
o = URIRef(triple['o']['value'])
elif to == 'literal':
o = Literal(triple['o']['value'])
if dto:
o.datatype = URIRef(dto)
elif ts == 'bnode':
o = BNode(vo)
#logging.debug(o)
g.add((s,p,o))
logging.debug(g.serialize(format='turtle'))
return g
示例12: test_n3
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
def test_n3(self):
g = Graph()
g.add((URIRef("http://example.com/foo"),
URIRef("http://example.com/bar"),
URIRef("http://example.com/baz")))
n3 = g.serialize(format="n3")
self.assertTrue("<http://example.com/foo> ns1:bar <http://example.com/baz> ." in n3)
示例13: createTestOntGraph
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
def createTestOntGraph():
graph = Graph()
graph.bind('ex',EX_NS,True)
Individual.factoryGraph = graph
kneeJoint = EX_CL.KneeJoint
joint = EX_CL.Joint
knee = EX_CL.Knee
isPartOf = Property(EX_NS.isPartOf)
graph.add((isPartOf.identifier,RDF.type,OWL_NS.TransitiveProperty))
structure = EX_CL.Structure
leg = EX_CL.Leg
hasLocation = Property(EX_NS.hasLocation,subPropertyOf=[isPartOf])
# graph.add((hasLocation.identifier,RDFS.subPropertyOf,isPartOf.identifier))
kneeJoint.equivalentClass = [joint & (isPartOf|some|knee)]
legStructure = EX_CL.LegStructure
legStructure.equivalentClass = [structure & (isPartOf|some|leg)]
structure += leg
structure += joint
locatedInLeg = hasLocation|some|leg
locatedInLeg += knee
# print graph.serialize(format='n3')
# newGraph = Graph()
# newGraph.bind('ex',EX_NS,True)
# newGraph,conceptMap = StructuralTransformation(graph,newGraph)
# revDict = dict([(v,k) for k,v in conceptMap.items()])
# Individual.factoryGraph = newGraph
# for oldConceptId ,newConceptId in conceptMap.items():
# if isinstance(oldConceptId,BNode):
# oldConceptRepr = repr(Class(oldConceptId,graph=graph))
# if oldConceptRepr.strip() == 'Some Class':
# oldConceptRepr = manchesterSyntax(
# oldConceptId,
# graph)
# print "%s -> %s"%(
# oldConceptRepr,
# newConceptId
# )
#
# else:
# print "%s -> %s"%(
# oldConceptId,
# newConceptId
# )
#
# for c in AllClasses(newGraph):
# if isinstance(c.identifier,BNode) and c.identifier in conceptMap.values():
# print "## %s ##"%c.identifier
# else:
# print "##" * 10
# print c.__repr__(True)
# print "################################"
return graph
示例14: _sparql_construct
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
def _sparql_construct(self, q, cursor):
g = Graph()
with cursor:
results = cursor.execute(q.encode("utf-8"))
with cursor as resolver:
for result in results:
g.add(resolve(resolver, x) for x in result)
return g
示例15: test_conjunction
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import add [as 别名]
def test_conjunction(self):
graph = self.open_graph()
self.add_stuff_in_multiple_contexts(graph)
triple = (pizza, likes, pizza)
# add to context 1
g1 = Graph(graph.store, context1)
g1.add(triple)
self.assertEquals(len(graph), len(g1))