Select Git revision
ontology_utils.py 1.23 KiB
#!/usr/bin/python3.10
# -*-coding:Utf-8 -*
#==============================================================================
# Ontology Utilities
#------------------------------------------------------------------------------
# --
#==============================================================================
from rdflib import Graph
def harmonize_prefixes(graph, source_uri, target_uri):
for s, p, o in graph.triples((None, None, None)):
s = s if not s.startswith(source_uri) else s.replace(source_uri, target_uri)
p = p if not p.startswith(source_uri) else p.replace(source_uri, target_uri)
o = o if not isinstance(o, str) or not o.startswith(source_uri) else o.replace(source_uri, target_uri)
graph.add((s, p, o))
return graph
def extract_prefixes_from_graph(graph):
return {prefix: namespace for prefix, namespace in graph.namespaces()}
def uri_to_short_form(uri, prefix_mappings, graph_prefixes):
for prefix, *uris in prefix_mappings:
for u in uris:
if u in uri:
return f"{prefix}:{uri.replace(u, '')}"
for prefix, namespace in graph_prefixes.items():
if namespace in uri:
return f"{prefix}:{uri.replace(namespace, '')}"
return uri