本文整理汇总了Python中rdflib.Graph.predicate_objects方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.predicate_objects方法的具体用法?Python Graph.predicate_objects怎么用?Python Graph.predicate_objects使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.Graph
的用法示例。
在下文中一共展示了Graph.predicate_objects方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RDFPage
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import predicate_objects [as 别名]
class RDFPage(Page):
format = None
def __init__(self, response):
self.data = Graph()
self.links = FilterableList()
self.queries = FilterableList(base_url=response.url)
super(RDFPage, self).__init__(response)
def extract_data(self):
self.data = Graph()
self.data.parse(data=self.response.text, format=self.format, publicID=self.url)
def extract_links(self):
for p, o in self.data.predicate_objects(URIRef(self.url)):
if isinstance(o, URIRef):
link = Link(p.toPython(), o.toPython())
self.links.append(link)
def extract_queries(self):
rows = self.data.query('''
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX schema: <http://schema.org/>
PREFIX hydra: <http://www.w3.org/ns/hydra/core#>
SELECT ?rel ?template
WHERE {
?url ?rel ?action .
?action rdf:type hydra:IriTemplate .
?action hydra:template ?template .
}
''')
for rel, template in rows:
self.queries.append(Query(str(rel), str(template), base_url=self.response.url))
示例2: __init__
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import predicate_objects [as 别名]
def __init__(self, entryuri: URIRef, g: Graph):
""" An individual manifest entry
:param entryuri: URI of the entry
:param g: graph containing the entry
"""
self.g = g
self.entryuri = entryuri
action = self._single_obj(mf.action)
assert action, "Invalid action list in entry"
self.action_ = {p: o for p, o in g.predicate_objects(action)}
assert self.action_, "No actions"
示例3: visualizeDocumentGraph
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import predicate_objects [as 别名]
def visualizeDocumentGraph(guri):
## BUG: if we let getContextGraph have its default result
## format, 'n3', the graph we get back contains errors eg.
## <http://chartex.org/chartex-schema#Site_7820> rdf:type
## <http://chartex.org/chartex-schema#Transaction_7818> . I
## can't explain this, but if we supply a result format:
## "application/rdf+xml" this doesn't happen. Moreover, this
## doesn't happen when querying the ADS store, why?
gstring = getContextGraph(guri, "application/rdf+xml")
g = Graph()
g.parse(data=gstring)
dgsvg = makedot(g).draw(format='svg', prog='twopi')
dname = g.objects(None, chartex.File).next() + '.txt'
try:
dtext = getText(dname, root=DATADIR).next()
except:
dtext = "couldn't find the damned thing anywhere. drat!"
cdata = json.loads(singleDocConfidenceData(guri))['values']
confidenceObj = {}
for x in cdata:
if x[0] not in confidenceObj:
confidenceObj[x[0]] = [{'obj':x[1], 'file':x[2], 'confidence':x[3], 'text':x[4]}]
else:
confidenceObj[x[0]].append({'obj':x[1], 'file':x[2], 'confidence':x[3], 'text':x[4]})
d = {
'svg': dgsvg,
'n3': g.serialize(format='n3'),
'entityAttributes':
{s:{p.partition('#')[-1]:str(o) for p,o in g.predicate_objects(s) if isinstance(o,Literal)} for s in set(g.subjects())},
'entityRelations':
{s:{p.partition('#')[-1]:str(o) for p,o in g.predicate_objects(s) if not isinstance(o,Literal) and not p == RDF.type} for s in set(g.subjects())},
'charterText': dtext,
'confidence': confidenceObj
}
return json.dumps(d)
示例4: visualizeDocumentGraph
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import predicate_objects [as 别名]
def visualizeDocumentGraph(guri):
gstring = getContextGraph(guri, "application/rdf+xml")
g = Graph()
g.parse(data=gstring)
dgsvg = makedot(g).draw(format="svg", prog="twopi")
dname = g.objects(None, chartex.File).next() + ".txt"
try:
dtext = getText(dname, root=DATADIR).next()
except:
dtext = "couldn't find the damned thing anywhere. drat!"
cdata = json.loads(singleDocConfidenceData(guri))["values"]
confidenceObj = {}
for x in cdata:
if x[0] not in confidenceObj:
confidenceObj[x[0]] = [{"obj": x[1], "file": x[2], "confidence": x[3], "text": x[4]}]
else:
confidenceObj[x[0]].append({"obj": x[1], "file": x[2], "confidence": x[3], "text": x[4]})
d = {
"svg": dgsvg,
"n3": g.serialize(format="n3"),
"entityAttributes": {
s: {p.partition("#")[-1]: str(o) for p, o in g.predicate_objects(s) if isinstance(o, Literal)}
for s in set(g.subjects())
},
"entityRelations": {
s: {
p.partition("#")[-1]: str(o)
for p, o in g.predicate_objects(s)
if not isinstance(o, Literal) and not p == RDF.type
}
for s in set(g.subjects())
},
"charterText": dtext,
"confidence": confidenceObj,
}
return json.dumps(d)
示例5: HydraPage
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import predicate_objects [as 别名]
class HydraPage(Page):
def __init__(self, response):
self.data = Graph()
self.links = FilterableList()
super(HydraPage, self).__init__(response)
def extract_data(self):
self.data.parse(data=self.response.text, format='json-ld', identifier=self.url)
def extract_links(self):
for p, o in self.data.predicate_objects(URIRef(self.url)):
if isinstance(o, URIRef):
link = Link(p.toPython(), o.toPython())
self.links.append(link)
示例6: save
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import predicate_objects [as 别名]
def save(eye_dump):
"""Place the euler output into the ontology"""
dump_graph = Graph()
dump_graph.parse(data=eye_dump, format='n3')
ts = Namespace("file://%s/infer-triplestore#" % ONTOLOGY_DIR)
for action, formula in dump_graph.predicate_objects(ts['n3store']):
if action in (ts['update'], ts['add'], ts['remove']):
for s, p, o in formula:
if action == ts['update']:
graph.set((s, p, o))
elif action == ts['add']:
graph.add((s, p, o))
elif action == ts['remove']:
graph.remove((s, p, o))
示例7: MockSyncedGraph
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import predicate_objects [as 别名]
class MockSyncedGraph(object):
"""
Lets users of SyncedGraph mostly work. Doesn't yet help with any
testing of the rerun-upon-graph-change behavior.
"""
def __init__(self, n3Content):
self._graph = Graph()
self._graph.parse(StringInputSource(n3Content), format='n3')
def addHandler(self, func):
func()
def value(self, subject=None, predicate=RDF.value, object=None,
default=None, any=True):
if object is not None:
raise NotImplementedError()
return self._graph.value(subject, predicate, object=object,
default=default, any=any)
def objects(self, subject=None, predicate=None):
return self._graph.objects(subject, predicate)
def label(self, uri):
return self.value(uri, RDFS.label)
def subjects(self, predicate=None, object=None):
return self._graph.subjects(predicate, object)
def predicate_objects(self, subject):
return self._graph.predicate_objects(subject)
def items(self, listUri):
"""generator. Having a chain of watchers on the results is not
well-tested yet"""
chain = set([listUri])
while listUri:
item = self.value(listUri, RDF.first)
if item:
yield item
listUri = self.value(listUri, RDF.rest)
if listUri in chain:
raise ValueError("List contains a recursive rdf:rest reference")
chain.add(listUri)
def contains(self, triple):
return triple in self._graph
示例8: RDFModel
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import predicate_objects [as 别名]
#.........这里部分代码省略.........
elif isinstance(key, str) and ":" in key:
ns, label = key.split(":")
ns = self.ns_dict.get(ns)
predicate = URIRef("{}/{}".format(str(ns).rstrip('/'), label))
else:
raise ValueError("unknown predicate key in mapping dict: {} => ".format(key, value))
if type(value) in [str, float, int] and value:
if isinstance(value, str) and any([value.startswith(uri_prefix) for uri_prefix in ["http", "urn"]]):
value = URIRef(value)
else:
value = Literal(value)
elif type(value) in [Literal, URIRef]:
value = value
else:
logger.warn("Unsupported datatype {} for value {}".format(type(value), value))
if value:
graph.add((subject, predicate, value))
graph.namespace_manager = namespace_manager
return graph
def get_graph(self, acceptance=False, target_uri=None):
if not self.graph:
self.graph = Graph(identifier=URIRef(self.named_graph))
self.graph.namespace_manager = namespace_manager
if acceptance and self.acceptance_rdf:
self.graph.parse(data=self.acceptance_rdf, format="nt")
elif self.source_rdf:
self.graph.parse(data=self.source_rdf, format="nt")
else:
self.graph = self._populate_graph()
if target_uri and target_uri != self.document_uri:
g = Graph(identifier=URIRef(self.named_graph))
subject = URIRef(target_uri)
for p, o in self.graph.predicate_objects(subject=subject):
g.add((subject, p, o))
self.graph = g
self._add_about_triples(self.graph)
return self.graph
def get_nquads_string(self):
graph = self.get_graph()
nquads = []
for triple in graph:
nquads.append(_nq_row(triple, graph.identifier))
return "".join(nquads)
def get_triples(self, acceptance=False):
# todo use switch between acceptance or production
source_rdf = self.acceptance_rdf if acceptance and self.acceptance_rdf else self.source_rdf
return source_rdf.decode('utf-8'), self.named_graph
def _generate_doc_type(self):
return "{}_{}".format(self.__class__._meta.app_label, self.__class__._meta.model_name)
@staticmethod
def get_object_from_sparql_result(value_dict):
if len(list(value_dict.keys())) == 1:
value_dict = list(value_dict.values())[0]
obj_type = value_dict.get('type', "literal")
if obj_type == "literal" or obj_type == "typed-literal":
language = value_dict['xml:lang'] if "xml:lang" in value_dict else None
datatype = value_dict['datatype'] if "datatype" in value_dict else None
obj = Literal(
value_dict['value'],
lang=language,
datatype=datatype
示例9: __init__
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import predicate_objects [as 别名]
#.........这里部分代码省略.........
if location and not format:
format = rdflib.util.guess_format(location)
# hacky, hacky, hacky
try:
self.graph.parse(source, publicID, format, location, file, data, **args)
except rdflib.plugin.PluginException:
# if that failed, try each of them
formats = ['xml', 'turtle', 'trix', 'rdfa1.1', 'rdfa1.0', 'rdfa', 'nt', 'nquads', 'n3', 'microdata',
'mdata', 'hturtle', 'html']
for fmt in formats:
try:
self.graph.parse(source, publicID, fmt, location, file, data, **args)
return
except Exception:
pass
# looks like none of them worked
raise rdflib.plugin.PluginException("No parser plugin found for ontology.")
def _load_uri(self):
"""
loads the ontology uri from the graph; chooses the one with the most triples if there are multiples
:return:
"""
uris = [uri for uri in self.graph.subjects(RDF.type, OWL.Ontology)]
# more than one ontology in the file; choosing one with most triples as canonical
if len(uris) > 1:
canon_uri = uris[0]
canon_num = 0
for uri in uris:
tuples = [(pred, obj) for (pred, obj) in self.graph.predicate_objects(uri)]
num = len(tuples)
if num > canon_num:
canon_num = num
canon_uri = uri
return canon_uri
elif len(uris) > 0:
return uris[0]
def _load_indirects(self):
"""
recursively loads all of the imports of any of the direct imports
:return:
"""
indirects = set()
for ont in self.direct_imports:
indirects |= ont.indirect_imports | ont.direct_imports
return indirects
def _load_directs(self):
"""
loads all of the direct imports, creating ontologies for each of them
:return:
"""
uris = [o for o in self.graph.objects(self.uri, OWL.imports)]
entities = set()
for uri in uris:
示例10: isinstance
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import predicate_objects [as 别名]
cilla_to_musa[cconc] = mconc
break
# remove Swedish data from MUSA
for s,p,o in musa.triples((None,None,None)):
if isinstance(o, Literal) and o.language == 'sv':
musa.remove((s,p,o))
# merge Cilla data to MUSA
for cconc in cilla.subjects(RDF.type, SKOS.Concept):
mconc = cilla_to_musa.get(cconc, None)
if mconc is None:
print >>sys.stderr, ("No MUSA concept found for CILLA concept %s '%s'" % (cconc, find_label(cilla, cconc, 'sv'))).encode('UTF-8')
continue
for p,o in cilla.predicate_objects(cconc):
if o.startswith(CILLA):
if o in cilla_to_musa:
o = cilla_to_musa[o]
else:
continue
if isinstance(o, Literal) and o.language == 'fi':
continue
if p == DCT.created:
musats = musa.value(mconc, p, None)
if musats > o:
musa.remove((mconc, p, musats))
# use the older timestamp from CILLA instead
else:
continue # use the timestamp from MUSA, forget this CILLA ts
示例11: Exception
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import predicate_objects [as 别名]
if (subj, pred, obj) not in g:
raise Exception("Iterator / Container Protocols are Broken!!")
print("\n\nChairs:\n\n")
# Find Triples in which an instance of the type Chair is defined
for chairs in g.subjects(RDF.type,chair):
print("------------------------------------------\n")
print("Found a Chair\n"+ chairs +"\n")
numOfChairs += 1
print("------------------------------------------")
# Search all predicates of this instance
print("### Predicates ###\n\n")
for pred,obj in g.predicate_objects(chairs):
# Look for Alternative References
if (pred==altRefPred):
print("# Lexical Reference #\n")
for o in g.objects(obj,lexicalRef):
print("Alternative: "+o+"\n")
# Look for Preferred Lexical Ref
if (pred == prefRefPred):
for o in g.objects(obj,lexicalRef):
print("*Favourite*: "+o+"\n")
# Look for size
if (pred == sizePred):
print("# Dimensions #\n")
示例12: __init__
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import predicate_objects [as 别名]
class Model:
def __init__(self):
self.graph = Graph()
self.loaded = set()
def load(self, source, format=None):
if source not in self.loaded:
self.loaded.add(source)
try:
self.graph.parse(source, format=format)
except Exception as e:
print e
return False
return True
def size(self):
return len(self.graph)
def pred(self, subj):
return list(set(self.graph.predicates(subj)))
def types(self):
return set(self.graph.objects(predicate=RDF.type))
def contains_resource(self, ref):
resources = filter(lambda x: type(x) == URIRef, self.graph.all_nodes())
return ref in resources
def get_resource_objects(self, subj, pred):
return filter(lambda x: type(x) == URIRef, self.graph.objects(subj, pred))
def get_objects(self, subj, pred):
return list(self.graph.objects(subj, pred))
def get_subjects(self, pred, obj):
return list(self.graph.subjects(pred, obj))
def get_properties(self, subj):
properties = {}
for pred, obj in self.graph.predicate_objects(subj):
if pred in properties:
properties[pred].append(obj)
else:
properties[pred] = [obj]
return properties
def get_reverse_properties(self, obj):
properties = {}
for subj, pred in self.graph.subject_predicates(obj):
if pred in properties:
properties[pred].append(subj)
else:
properties[pred] = [subj]
return properties
def norm(self, ref):
return self.graph.namespace_manager.normalizeUri(ref) if ref else None
def to_uriref(self, string):
"""Expand QName to UriRef based on existing namespaces."""
if not string:
return None
elif re.match('[^:/]*:[^:/]+', string):
prefix, name = string.split(':')
try:
namespace = dict(self.graph.namespaces())[prefix]
return namespace + name
except:
return None
else:
return URIRef(string)
示例13: search
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import predicate_objects [as 别名]
seedclass = stats[0][0]
print >>sys.stderr, "Most common domain ontology class used as starting point:", seedclass
# Determine the bounds of the domain-specific ontology by performing a
# non-recursive breadth-first search (except a set is used instead of a FIFO
# so the traversal order is a bit random). Code adapted from Skosify.
to_search = set([seedclass])
seen = set()
while len(to_search) > 0:
res = to_search.pop()
if res in seen: continue
seen.add(res)
# res as subject
for p,o in g.predicate_objects(res):
out.add((res,p,o))
# for cl in g.objects(res, RDF.type):
# out.add((res,RDF.type,cl))
if isinstance(p, URIRef) and p not in seen and is_domainont(p):
to_search.add(p)
if o not in seen:
if isinstance(o, BNode) or (isinstance(o, URIRef) and is_domainont(o)):
to_search.add(o)
# res as predicate
# for s,o in g.subject_objects(res):
# out.add((s,res,o))
# if isinstance(s, URIRef) and s not in seen and is_domainont(s):
# to_search.add(s)
# if isinstance(o, URIRef) and o not in seen and is_domainont(o):