本文整理汇总了Python中rdflib.ConjunctiveGraph方法的典型用法代码示例。如果您正苦于以下问题:Python rdflib.ConjunctiveGraph方法的具体用法?Python rdflib.ConjunctiveGraph怎么用?Python rdflib.ConjunctiveGraph使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib
的用法示例。
在下文中一共展示了rdflib.ConjunctiveGraph方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: to_rdf
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def to_rdf(self, edge_info, edge):
g = Graph()
def _add_resource(d, p, r, r_type):
if r_type is not None:
g.add((r, RDF.type, URIRef(r_type)))
g.add((d, URIRef(p), r))
if edge_info["range_tile_data"] is not None:
res_insts = edge_info["range_tile_data"]
if not isinstance(res_insts, list):
res_insts = [res_insts]
for res_inst in res_insts:
rangenode = self.get_rdf_uri(None, res_inst)
try:
res_inst_obj = models.ResourceInstance.objects.get(pk=res_inst["resourceId"])
r_type = res_inst_obj.graph.node_set.get(istopnode=True).ontologyclass
except models.ResourceInstance.DoesNotExist:
# This should never happen excpet if trying to export when the
# referenced resource hasn't been saved to the database yet
r_type = edge.rangenode.ontologyclass
_add_resource(edge_info["d_uri"], edge.ontologyproperty, rangenode, r_type)
return g
示例2: stringify_node
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def stringify_node(graph, node, ns_manager=None, recursion=0):
if ns_manager is None:
ns_manager = graph.namespace_manager
if isinstance(ns_manager, rdflib.Graph):
#json-ld loader can set namespace_manager to the conjunctive graph itself.
ns_manager = ns_manager.namespace_manager
ns_manager.bind("sh", SH, override=False, replace=False)
if isinstance(node, rdflib.Literal):
return stringify_literal(graph, node, ns_manager=ns_manager)
if isinstance(node, rdflib.BNode):
if isinstance(graph, (rdflib.ConjunctiveGraph, rdflib.Dataset)):
graph = find_node_named_graph(graph, node)
return stringify_blank_node(graph, node, ns_manager=ns_manager,
recursion=recursion+1)
if isinstance(node, rdflib.URIRef):
return node.n3(namespace_manager=ns_manager)
else:
node_string = str(node)
return node_string
示例3: clone_dataset
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def clone_dataset(source_ds, target_ds=None):
if target_ds and not isinstance(target_ds, (rdflib.Dataset, rdflib.ConjunctiveGraph)):
raise RuntimeError("when cloning a dataset, the target_ds must be a conjunctiveGraph or rdflib Dataset.")
default_union = source_ds.default_union
if target_ds is None:
target_ds = rdflib.Dataset(default_union=default_union)
named_graphs = [
rdflib.Graph(source_ds.store, i, namespace_manager=source_ds.namespace_manager)
if not isinstance(i, rdflib.Graph) else i for i in source_ds.store.contexts(None)
]
cloned_graphs = [
clone_graph(ng, rdflib.Graph(target_ds.store, ng.identifier, namespace_manager=target_ds.namespace_manager))
for ng in named_graphs
]
default_context_id = target_ds.default_context.identifier
for g in cloned_graphs:
if g.identifier == default_context_id:
target_ds.store.remove_graph(target_ds.default_context)
target_ds.default_context = g
target_ds.add_graph(g)
return target_ds
示例4: clone_graph
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def clone_graph(source_graph, target_graph=None, identifier=None):
"""
Make a clone of the source_graph by directly copying triples from source_graph to target_graph
:param source_graph:
:type source_graph: rdflib.Graph
:param target_graph:
:type target_graph: rdflib.Graph|None
:param identifier:
:type identifier: str | None
:return: The cloned graph
:rtype: rdflib.Graph
"""
if isinstance(source_graph, (rdflib.Dataset, rdflib.ConjunctiveGraph)):
return clone_dataset(source_graph, target_ds=target_graph)
if target_graph is None:
g = rdflib.Graph(identifier=identifier)
for p, n in source_graph.namespace_manager.namespaces():
g.namespace_manager.bind(p, n, override=True, replace=True)
else:
g = target_graph
for p, n in source_graph.namespace_manager.namespaces():
g.namespace_manager.bind(p, n, override=False, replace=False)
for t in iter(source_graph):
g.add(t)
return g
示例5: mix_datasets
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def mix_datasets(base_ds, extra_ds, target_ds=None):
default_union = base_ds.default_union
base_named_graphs = base_ds.contexts()
if target_ds is None:
target_ds = rdflib.Dataset(default_union=default_union)
if isinstance(extra_ds, (rdflib.Dataset, rdflib.ConjunctiveGraph)):
mixin_graphs = list(extra_ds.contexts())
else:
mixin_graphs = [extra_ds]
mixed_graphs = []
for mg in mixin_graphs:
mod_named_graphs = [mix_graphs(g, mg, target_graph=rdflib.Graph(store=target_ds.store, identifier=g.identifier)) for g in base_named_graphs]
mixed_graphs.extend(mod_named_graphs)
default_context_id = target_ds.default_context.identifier
for m in mixed_graphs:
if m.identifier == default_context_id:
target_ds.store.remove_graph(target_ds.default_context)
target_ds.default_context = m
target_ds.add_graph(m)
return target_ds
示例6: __init__
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def __init__(self, data_graph, *args, shacl_graph=None,
ont_graph=None, options=None, **kwargs):
options = options or {}
self._load_default_options(options)
self.options = options
self.logger = options['logger']
self.pre_inferenced = kwargs.pop('pre_inferenced', False)
assert isinstance(data_graph, rdflib.Graph),\
"data_graph must be a rdflib Graph object"
self.data_graph = data_graph
self._target_graph = None
self.ont_graph = ont_graph
self.data_graph_is_multigraph = isinstance(self.data_graph, (rdflib.Dataset, rdflib.ConjunctiveGraph))
if self.ont_graph is not None and \
isinstance(self.ont_graph, (rdflib.Dataset, rdflib.ConjunctiveGraph)):
self.ont_graph.default_union = True
if shacl_graph is None:
shacl_graph = clone_graph(data_graph, identifier='shacl')
assert isinstance(shacl_graph, rdflib.Graph),\
"shacl_graph must be a rdflib Graph object"
self.shacl_graph = ShapesGraph(shacl_graph, self.logger)
示例7: __init__
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def __init__(self, graph, logger=None):
"""
ShapesGraph
:param graph:
:type graph: rdflib.Graph
:param logger:
:type logger: logging.Logger|None
"""
assert isinstance(graph, (rdflib.Dataset, rdflib.ConjunctiveGraph, rdflib.Graph))
self.graph = graph
if isinstance(self.graph, rdflib.Dataset):
self.graph.default_union = True
if logger is None:
logger = logging.getLogger(__name__)
self.logger = logger
self._node_shape_cache = {}
self._shapes = None
self._custom_constraints = None
self._add_system_triples()
示例8: __init__
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def __init__(self, parentContainer, localId, dataDir):
"""
Initialize dataset, using the passed dict of sources
[{source,format}] see rdflib.parse() for more
If path is set, this backend will load itself
"""
super(RdfPhenotypeAssociationSet, self).__init__(
parentContainer, localId)
# initialize graph
self._rdfGraph = rdflib.ConjunctiveGraph()
# save the path
self._dataUrl = dataDir
self._scanDataFiles(dataDir, ['*.ttl'])
# extract version
cgdTTL = rdflib.URIRef("http://data.monarchinitiative.org/ttl/cgd.ttl")
versionInfo = rdflib.URIRef(
u'http://www.w3.org/2002/07/owl#versionInfo')
self._version = None
for _, _, obj in self._rdfGraph.triples((cgdTTL, versionInfo, None)):
self._version = obj.toPython()
示例9: make_graph_from_json_ld
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def make_graph_from_json_ld(json_ld, id=None):
"""Returns a graph made from JSON-LD."""
if isinstance(json_ld, dict):
if not id and 'id' in json_ld:
# ID for graph is in the JSON-LD
id = json_ld['id']
elif not id and '@id' in json_ld:
# ID for graph is in the JSON-LD
id = json_ld['@id']
json_ld = json.dumps(json_ld, ensure_ascii=False)
if isinstance(id, str):
id = URIRef(id)
try:
g = ConjunctiveGraph().parse(
data=json_ld,
publicID=id,
format='json-ld')
except:
return None
return g
示例10: test_empty_boolean
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def test_empty_boolean():
csvw = CSVW(csv_path="tests/empty.csv",
metadata_path="tests/empty.bool.csv-metadata.json")
rdf_output = csvw.to_rdf()
g = ConjunctiveGraph()
g.parse(data=rdf_output, format="turtle")
assert len(g) == 2
assert len(list(g.triples((None, None, Literal(False))))) == 2
csvw = CSVW(csv_path="tests/empty.csv",
metadata_path="tests/empty.invalid_base.csv-metadata.json")
rdf_output = csvw.to_rdf()
g = ConjunctiveGraph()
g.parse(data=rdf_output, format="turtle")
assert len(g) == 0
示例11: test_time
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def test_time():
with CSVW(csv_path="tests/datatypes.time.csv",
metadata_path="tests/datatypes.time.csv-metadata.json") as csvw:
rdf_output = csvw.to_rdf()
g = ConjunctiveGraph()
g.parse(data=rdf_output, format="turtle")
NS = Namespace('https://www.example.org/')
time1_lit = Literal("19:30:00", datatype=XSD.time)
assert len(list(g.triples((NS['event/1'], NS['time1'], time1_lit)))) == 1
time2_lit = Literal("09:30:10.5", datatype=XSD.time)
assert len(list(g.triples((NS['event/1'], NS['time2'], time2_lit)))) == 1
time3_lit = Literal("10:30:10Z", datatype=XSD.time)
assert len(list(g.triples((NS['event/1'], NS['time3'], time3_lit)))) == 1
time4_lit = Literal("11:30:10-06:00", datatype=XSD.time)
assert len(list(g.triples((NS['event/1'], NS['time4'], time4_lit)))) == 1
time5_lit = Literal("04:30:10+04:00", datatype=XSD.time)
assert len(list(g.triples((NS['event/1'], NS['time5'], time5_lit)))) == 1
示例12: test_date
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def test_date():
with CSVW(csv_path="tests/datatypes.date.csv",
metadata_path="tests/datatypes.date.csv-metadata.json") as csvw:
rdf_output = csvw.to_rdf()
g = ConjunctiveGraph()
g.parse(data=rdf_output, format="turtle")
date1_lit = Literal("2017-01-09", datatype=XSD.date)
assert len(list(g.triples((NS['event/1'], NS['date1'], date1_lit)))) == 1
date2_lit = Literal("2017-01-10Z", datatype=XSD.date)
assert len(list(g.triples((NS['event/1'], NS['date2'], date2_lit)))) == 1
date3_lit = Literal("2017-01-11", datatype=XSD.date)
assert len(list(g.triples((NS['event/1'], NS['date3'], date3_lit)))) == 1
date4_lit = Literal("2002-09-24-06:00", datatype=XSD.date)
assert len(list(g.triples((NS['event/1'], NS['date4'], date4_lit)))) == 1
date5_lit = Literal("2002-09-24+04:00", datatype=XSD.date)
assert len(list(g.triples((NS['event/1'], NS['date5'], date5_lit)))) == 1
示例13: test_bool_with_format
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def test_bool_with_format():
csvw = CSVW(csv_path="tests/datatypes.bool.csv",
metadata_path="tests/datatypes.bool.csv-metadata.json")
rdf_output = csvw.to_rdf()
g = ConjunctiveGraph()
g.parse(data=rdf_output, format="turtle")
true_lit = Literal(True, datatype=XSD.boolean)
false_lit = Literal(False, datatype=XSD.boolean)
assert len(list(g.triples((NS['event/1'], NS['bool1'], true_lit)))) == 1
assert len(list(g.triples((NS['event/1'], NS['bool2'], true_lit)))) == 1
assert len(list(g.triples((NS['event/1'], NS['bool3'], true_lit)))) == 1
assert len(list(g.triples((NS['event/2'], NS['bool1'], false_lit)))) == 1
assert len(list(g.triples((NS['event/2'], NS['bool2'], false_lit)))) == 1
assert len(list(g.triples((NS['event/2'], NS['bool3'], false_lit)))) == 1
assert len(list(g.triples((NS['event/3'], NS['bool1'], false_lit)))) == 1
assert len(list(g.triples((NS['event/3'], NS['bool2'], false_lit)))) == 1
assert len(list(g.triples((NS['event/3'], NS['bool3'], false_lit)))) == 1
示例14: test_null_values_with_multiple_strings
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def test_null_values_with_multiple_strings():
csvw = CSVW(csv_path="tests/null1.csv",
metadata_path="tests/null1.multiple.csv-metadata.json")
rdf_contents = csvw.to_rdf()
g = ConjunctiveGraph()
g.parse(data=rdf_contents, format="turtle")
all_objects = {x for x in g.objects()}
assert Literal('null_key', datatype=XSD.token) not in all_objects
assert Literal('null_sector') not in all_objects
assert Literal('null_id', datatype=XSD.token) not in all_objects
for id in ['10', '11', '12', '13']:
assert Literal(id, datatype=XSD.token) not in all_objects
all_preds = {x for x in g.predicates()}
assert id_uri not in all_preds
assert Literal('1', datatype=XSD.token) not in all_objects
示例15: verify_rdf
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import ConjunctiveGraph [as 别名]
def verify_rdf(rdf_output):
ids_ns = Namespace("http://foo.example.org/CSV/People-IDs/")
ages_ns = Namespace("http://foo.example.org/CSV/People-Ages/")
g = ConjunctiveGraph()
g.parse(data=rdf_output, format="turtle")
all_subjects = {x for x in g.subjects()}
assert len(all_subjects) == 2
bob_subj = ids_ns['1']
joe_subj = ids_ns['2']
assert bob_subj in all_subjects
assert joe_subj in all_subjects
# Bob's details
assert len([g.triples((bob_subj, ids_ns.id, Literal(1)))]) == 1
assert len([g.triples((bob_subj, ids_ns.name, Literal("Bob")))]) == 1
assert len([g.triples((bob_subj, ages_ns.age, Literal(34)))]) == 1
# Joe's details
assert len([g.triples((joe_subj, ids_ns.id, Literal(2)))]) == 1
assert len([g.triples((joe_subj, ids_ns.name, Literal("Joe")))]) == 1
assert len([g.triples((joe_subj, ages_ns.age, Literal(54)))]) == 1