本文整理汇总了Python中rdflib.ConjunctiveGraph.add方法的典型用法代码示例。如果您正苦于以下问题:Python ConjunctiveGraph.add方法的具体用法?Python ConjunctiveGraph.add怎么用?Python ConjunctiveGraph.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.ConjunctiveGraph
的用法示例。
在下文中一共展示了ConjunctiveGraph.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fill_graph_by_subject
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
def fill_graph_by_subject(basegraph, newgraph, subject, loop_count=0):
"""
Fills an Graph with all triples with an certain subject. Includes the necessary triples for the objects until the deepth of 5.
:param basegraph: Graph with the data for the new Graph
:param newgraph: Instance of the new Graph
:param subject: subject of triples which is looked for in the basegraph
:return: Graph
"""
subject_list=[BNode,URIRef]
if not issubclass(type(basegraph),Graph):
log.error("The given basegraph is not a subclass of Graph!")
return ConjunctiveGraph()
elif subject == "":
log.info("The given subject was empty. Returning the basegraph")
return basegraph
elif type(subject) not in subject_list:
log.info("The given subject was not of type BNode or URIRef. Returning the basegraph")
return basegraph
elif not issubclass(type(newgraph),Graph):
newgraph=ConjunctiveGraph()
loop_count += 1
for s, p, o in basegraph.triples((subject, None, None)):
newgraph.add((s, p, o))
if type(o) in subject_list and loop_count < 6: # it will do: (S1,P1,O1) -> if O1 has an own Description: (O1,P2,O2)... 5 times
newgraph = fill_graph_by_subject(basegraph, newgraph, o, loop_count)
return newgraph
示例2: Topic
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
class Topic(object):
def __init__(self, entity_name, entity_id):
'''
Constructor
'''
# Get the event page and compute its id
self.entity_id = entity_id
self.resource = LDES[self.entity_id]
# Create the graph
self.graph = ConjunctiveGraph()
self.graph.bind('swc', SWC)
self.graph.bind('cfp', CFP)
self.graph.bind('ical', ICAL)
self.graph.bind('foaf', FOAF)
self.graph.bind('dct', DCT)
self.graph.bind('lode', LODE)
# Declare the type of the resource
self.graph.add((self.resource, RDF.type, SIOCT['Tag']))
self.graph.add((self.named_graph(), DCT['modified'], Literal(datetime.now())))
def get_rdf_data(self):
return self.graph.serialize()
def named_graph(self):
return URIRef(NAMED_GRAPHS_BASE + self.entity_id + '.rdf')
def process(self, record, entity_url):
# Get the document
document = BeautifulSoup(urllib2.urlopen("http://eventseer.net" + entity_url).read())
del document
示例3: discussion_as_graph
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
def discussion_as_graph(self, discussion_id):
from assembl.models import Discussion, AgentProfile
local_uri = self.local_uri()
discussion = Discussion.get(discussion_id)
d_storage_name = self.discussion_storage_name()
d_graph_iri = URIRef(self.discussion_graph_iri())
v = get_virtuoso(self.session, d_storage_name)
discussion_uri = URIRef(
Discussion.uri_generic(discussion_id, local_uri))
subjects = [s for (s,) in v.query(
"""SELECT DISTINCT ?s WHERE {
?s assembl:in_conversation %s }""" % (discussion_uri.n3()))]
subjects.append(discussion_uri)
participant_ids = list(discussion.get_participants(True))
profiles = {URIRef(AgentProfile.uri_generic(id, local_uri))
for id in participant_ids}
subjects.extend(profiles)
# add pseudo-accounts
subjects.extend((URIRef("%sAgentAccount/%d" % (local_uri, id))
for id in participant_ids))
# print len(subjects)
cg = ConjunctiveGraph(identifier=d_graph_iri)
self.add_subject_data(v, cg, subjects)
# add relationships of non-pseudo accounts
for ((account, p, profile), g) in v.triples((None, SIOC.account_of, None)):
if profile in profiles:
cg.add((account, SIOC.account_of, profile, g))
# Tempting: simplify with this.
# cg.add((profile, FOAF.account, account, g))
for (s, o, g) in v.query(
'''SELECT ?s ?o ?g WHERE {
GRAPH ?g {?s catalyst:expressesIdea ?o } .
?o assembl:in_conversation %s }''' % (discussion_uri.n3())):
cg.add((s, CATALYST.expressesIdea, o, g))
return cg
示例4: get_rdf_template
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
def get_rdf_template(item_uri, item_id):
g = ConjunctiveGraph(identifier=item_uri)
g.bind('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')
g.bind('dcterms', 'http://purl.org/dc/terms/')
g.add((URIRef(item_uri), URIRef('http://purl.org/dc/terms/identifier'), Literal(item_id)))
data2 = g.serialize(format='xml', encoding="utf-8") + '\n'
return data2
示例5: Serializer
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
class Serializer(PythonSerializer):
"""
Convert a queryset to RDF
"""
internal_use_only = False
def end_serialization(self):
FOAF = Namespace('http://xmlns.com/foaf/0.1/')
DC = Namespace('http://purl.org/dc/elements/1.1/')
self.graph = ConjunctiveGraph()
self.options.pop('stream', None)
fields = filter(None, self.options.pop('fields','').split(','))
meta = None
subject = None
for object in self.objects:
if not fields:
fields = object['fields'].keys()
newmeta = object['model']
if newmeta != meta:
meta = newmeta
subject = BNode('%s.%s'%(FOAF[newmeta],object['pk']))
self.graph.add((subject,FOAF['pk'],Literal(object['pk'])))
for k in fields:
if k:
self.graph.add((subject,FOAF[k],Literal(object['fields'][k])))
def getvalue(self):
if callable(getattr(self.graph, 'serialize', None)):
return self.graph.serialize()
示例6: get_graph_from_sparql_results
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
def get_graph_from_sparql_results(sparql_json, named_graph=None):
if len(sparql_json['results']['bindings']) == 0:
return ConjunctiveGraph(), 0
sparql_vars = sparql_json['head']['vars']
if 'g' in sparql_vars:
if not named_graph:
named_graph = sparql_json['results']['bindings'][0]['g']['value']
sparql_vars.remove('g')
triple_levels = RDFModel.get_context_triples(sparql_json['head']['vars'])
nr_levels = len(triple_levels)
if named_graph:
named_graph = URIRef(named_graph)
graph = ConjunctiveGraph(identifier=named_graph)
graph.namespace_manager = namespace_manager
for binding in sparql_json['results']['bindings']:
binding_levels = RDFModel.get_context_levels(len(binding.keys()))
for s, p, o in triple_levels[:binding_levels]:
subject = URIRef(binding[s]['value'])
if binding[s]['type'] == 'bnode':
subject = BNode(binding[s]['value'])
predicate = URIRef(binding[p]['value'])
obj = RDFModel.get_object_from_sparql_result(binding[o])
graph.add((subject, predicate, obj))
# materialize inferences
for subject, obj in graph.subject_objects(
predicate=URIRef("http://www.openarchives.org/ore/terms/isAggregatedBy")):
graph.add((obj, URIRef("http://www.openarchives.org/ore/terms/aggregates"), subject))
graph.remove((subject, URIRef("http://www.openarchives.org/ore/terms/isAggregatedBy"), obj))
return graph, nr_levels
示例7: discussion_as_graph
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
def discussion_as_graph(self, discussion_id):
self.ensure_discussion_storage(None)
from assembl.models import Discussion
d_storage_name = self.discussion_storage_name()
d_graph_iri = URIRef(self.discussion_graph_iri())
v = get_virtuoso(self.session, d_storage_name)
discussion_uri = URIRef(
Discussion.uri_generic(discussion_id, self.local_uri()))
subjects = list(v.query(
"""SELECT DISTINCT ?s WHERE {
?s assembl:in_conversation %s }""" % (discussion_uri.n3())))
subjects.append([discussion_uri])
# print len(subjects)
cg = ConjunctiveGraph(identifier=d_graph_iri)
for (s,) in subjects:
# Absurdly slow. DISTINCT speeds up a lot, but I get numbers.
for p, o in v.query(
'SELECT ?p ?o WHERE { graph %s { %s ?p ?o }}' % (
d_graph_iri.n3(), s.n3())):
cg.add((s, p, o))
for (s, o, g) in v.query(
'''SELECT ?s ?o ?g WHERE {
GRAPH ?g {?s catalyst:expressesIdea ?o } .
?o assembl:in_conversation %s }''' % (discussion_uri.n3())):
cg.add((s, CATALYST.expressesIdea, o, g))
# TODO: Add roles
return cg
示例8: rdf_from_site
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
def rdf_from_site(site, rules=None):
'''
>>> from librarylink.util import rdf_from_site
>>> g = rdf_from_site('http://link.denverlibrary.org')
>>> s = g.serialize(format='json-ld', indent=2)
>>> with open('denverlibrary.ld.json', 'wb') as fp: fp.write(s)
>>> rules = {'ignore-predicates': ['http://bibfra.me/', 'http://library.link/'], 'rename-predicates': {'http://library.link/vocab/branchOf': 'http://schema.org/branch'}}
>>> g = rdf_from_site('http://link.denverlibrary.org', rules=rules)
>>> s = g.serialize(format='json-ld', indent=2)
>>> with open('denverlibrary.ld.json', 'wb') as fp: fp.write(s)
'''
from rdflib import ConjunctiveGraph, URIRef, Literal, RDF, RDFS
from versa.writer.rdf import mock_bnode, prep, RDF_TYPE
#Also requires: pip install rdflib-jsonld
rules = rules or {}
ignore_pred = rules.get('ignore-predicates', set())
rename_pred = rules.get('rename-predicates', {})
model, sitetext = load_rdfa_page(site)
if not model:
return None
g = ConjunctiveGraph()
#Hoover up everything with a type
for o, r, t, a in model.match():
for oldp, newp in rename_pred.items():
if r == oldp: r = newp
for igp in ignore_pred:
if r.startswith(igp):
break
else:
g.add(prep(o, r, t))
return g
示例9: query_graph
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
def query_graph(self, subj=None, pred=None, obj=None, exhaustive=False):
"""Return a graph of all triples with subect `sub`, predicate `pred`
OR object `obj. If `exhaustive`, return all subelements of the given
arguments (If sub is http://127.0.0.1/api/v1/wine/, return
http://127.0.0.1/api/v1/wine/{s} for all s). Arguments must be of type
URIRef or Literal"""
g = ConjunctiveGraph()
count = 0
if not isinstance(subj, list):
subj = [subj]
for sub in subj:
for uri_s, uri_p, uri_o in sorted(self.graph):
s, p, o = str(uri_s), str(uri_p), str(uri_o)
if exhaustive:
s = s.rpartition('/')[0]
p = p.rpartition('/')[0]
o = o.rpartition('/')[0]
else:
s = s[:-1] if s.endswith('/') else s
p = p[:-1] if p.endswith('/') else p
o = o[:-1] if o.endswith('/') else o
if (sub and sub == s) or (pred and pred == p) or (obj and obj == o):
g.add((uri_s, uri_p, uri_o))
count += 1
return g
示例10: update_mediator
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
def update_mediator(params):
#Write user metadata and save the rdf file
if not ('username' in params and params['username']):
return False
det = get_mediator_details(params['username'])
graph = Graph()
graph.parse(os.path.join(ag.mediatorsdir, '%s.rdf'%params['username']))
for prefix, url in namespaces.iteritems():
graph.bind(prefix, URIRef(url))
uri = URIRef(det['uri'])
if 'firstname' in params and params['firstname']:
graph.remove((uri, namespaces['foaf']['firstName'], None))
graph.add((uri, namespaces['foaf']['firstName'], Literal(params['firstname'])))
if 'lastname' in params and params['lastname']:
graph.remove((uri, namespaces['foaf']['lastName'], None))
graph.add((uri, namespaces['foaf']['lastName'], Literal(params['lastname'])))
if 'email' in params and params['email']:
graph.remove((uri, namespaces['foaf']['mbox'], None))
graph.add((uri, namespaces['foaf']['mbox'], Literal(params['email'])))
if 'title' in params and params['title']:
graph.remove((uri, namespaces['foaf']['title'], None))
graph.add((uri, namespaces['foaf']['title'], Literal(params['title'])))
if 'department' in params and params['department']:
graph.remove((uri, namespaces['dcterms']['isPartOf'], None))
department = params['department'].split(';')
for d in department:
graph.add((uri, namespaces['dcterms']['isPartOf'], Literal(d.strip())))
rdf_str = None
rdf_str = graph.serialize()
f = codecs.open(os.path.join(ag.mediatorsdir, '%s.rdf'%params['username']), 'w', 'utf-8')
f.write(rdf_str)
f.close()
return True
示例11: change_status
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
def change_status(vocabprefix, uri, predicate, message, action):
if not action in ['add', 'remove']:
return False
vocab_uri = URIRef(uri)
vocabdir = os.path.join(ag.vocabulariesdir, vocabprefix)
vocabstatusfile = os.path.join(vocabdir, "status.rdf")
if not os.path.isfile(vocabstatusfile):
return False
graph = Graph()
graph.parse(vocabstatusfile)
predicate = predicate.split(':')
ns = predicate[0]
term = predicate[1]
if message and (message.startswith('http://') or message.startswith('file://')):
message = URIRef(message)
elif message:
message = Literal(message)
if action == 'add':
for prefix, url in namespaces.iteritems():
graph.bind(prefix, URIRef(url))
graph.add((vocab_uri, namespaces[ns][term], message))
elif action == 'remove':
graph.remove((vocab_uri, namespaces[ns][term], message))
rdf_str = None
rdf_str = graph.serialize()
f = codecs.open(vocabstatusfile, 'w', 'utf-8')
f.write(rdf_str)
f.close()
return True
示例12: _RDFGraph
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
def _RDFGraph(self):
graph = Graph()
for k, v in self.__dict__.iteritems():
if k == "URL": continue
if k[0] == "_": continue
if hasattr(v, "URL"):
graph.add( ( URIRef(self.URL), pypeNS[k], URIRef(v.URL) ) )
return graph
示例13: as_graph
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
def as_graph(self, d_storage_name, graphs=()):
v = get_virtuoso(self.session, d_storage_name)
if not graphs:
graphs = v.contexts()
cg = ConjunctiveGraph()
for ctx in graphs:
for ((s, p, o), g) in v.triples((None,None,None), ctx):
cg.add((s, p, o, ctx))
return cg
示例14: load_sentence
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
def load_sentence(self, rdf_triples):
"""
Load the given triples into the triple store
"""
g = ConjunctiveGraph()
g.bind("base", BASE)
for triple in rdf_triples:
g.add(triple)
self.soh.add_triples(g, clear=True)
示例15: exportRDFGraph
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import add [as 别名]
def exportRDFGraph(mi):
g = ConjunctiveGraph()
bnodes = {}
for NSName, NSuriStr in mi.namespaceBindings.iteritems():
g.namespace_manager.bind(NSName, URIRef(NSuriStr))
modelAttrs = [model.__dict__[c] for c in model.__dict__.keys()]
knownTypes = dict([(c.classURI, c) for c in modelAttrs if hasattr(c, "classURI")])
knownInstances = dict([(i.URI, i) for i in modelAttrs if hasattr(i, "URI")])
# Assign blind nodes :
for s in mi.MainIdx.values():
if s.URI == None or isBlind(s):
snode = BNode()
bnodes[s.URI] = snode
for propName, propSet in s._props.iteritems():
for v in propSet:
if type(v) not in propSet.Lits and isBlind(v):
if not bnodes.has_key(v.URI):
vnode = BNode()
bnodes[v.URI] = vnode
for s in mi.MainIdx.values():
if not hasattr(s, "classURI") or s.classURI not in knownTypes.keys():
raise ExportException("Object "+str(s)+" has no classURI, or classURI is not known in the SAO model.")
# FIXME : Maybe use a Resource ?
if s.URI == None or isBlind(s):
snode = bnodes[s.URI]
else:
snode = URIRef(s.URI)
g.add((snode, RDF.type, URIRef(s.classURI)))
for propName, propSet in s._props.iteritems():
for v in propSet:
if not hasattr(propSet, "propertyURI"):
raise ExportException("Property "+str(propName)+" on object "+str(s)+" has no propertyURI !")
if type(v) not in propSet.Lits and not isinstance(v, Literal):
if not hasattr(v, "URI"):
raise ExportException("Property value "+str(v)+" is not a Literal, but has no URI !")
if isBlind(v):
g.add((snode, URIRef(propSet.propertyURI), bnodes[v.URI]))
else:
g.add((snode, URIRef(propSet.propertyURI), URIRef(v.URI)))
else:
if isinstance(v, Literal):
g.add((snode, URIRef(propSet.propertyURI), v))
else:
g.add((snode, URIRef(propSet.propertyURI), Literal(v)))
info("Added "+str(type(s))+" @ "+str(snode))
return g