本文整理汇总了Python中rdflib.Literal方法的典型用法代码示例。如果您正苦于以下问题:Python rdflib.Literal方法的具体用法?Python rdflib.Literal怎么用?Python rdflib.Literal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib
的用法示例。
在下文中一共展示了rdflib.Literal方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_rdf_concept_list
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def test_rdf_concept_list(self):
dt = self.DT.get_instance("concept-list")
concept_list = [
"d75977c1-635b-41d5-b53d-1c82d2237b67", # junk sculpture@en, has aat identifier
"4beb7055-8a6e-45a3-9bfb-32984b6f82e0", # "example document type"@en-us, no ext id}
]
edge_info = {}
edge_info["range_tile_data"] = concept_list
edge_info["r_uri"] = URIRef("http://vocab.getty.edu/aat/300047196")
edge_info["d_uri"] = URIRef("test")
edge = Mock()
edge.ontologyproperty = CIDOC_NS["P2_has_type"]
edge.rangenode.ontologyclass = CIDOC_NS["E55_Type"]
graph = dt.to_rdf(edge_info, edge)
edge_info["r_uri"] = ARCHES_NS["concepts/037daf4d-054a-44d2-9c0a-108b59e39109"]
graph += dt.to_rdf(edge_info, edge)
self.assertTrue((edge_info["d_uri"], edge.ontologyproperty, URIRef("http://vocab.getty.edu/aat/300047196")) in graph)
self.assertTrue((URIRef("http://vocab.getty.edu/aat/300047196"), RDFS.label, Literal("junk sculpture")) in graph)
self.assertTrue((edge_info["d_uri"], edge.ontologyproperty, ARCHES_NS["concepts/037daf4d-054a-44d2-9c0a-108b59e39109"]) in graph)
self.assertTrue((ARCHES_NS["concepts/037daf4d-054a-44d2-9c0a-108b59e39109"], RDFS.label, Literal("example document type")) in graph)
示例2: test_version_level_version_set_explicitly
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def test_version_level_version_set_explicitly(self):
self.dataset = Dataset(
identifier=self.identifier,
data_release_version=self.data_release_version,
ingest_name=self.identifier,
ingest_title=self.ingest_title,
ingest_url=self.ingest_url,
ingest_logo=self.ingest_logo_url,
ingest_description=self.ingest_description,
license_url=None,
data_rights=self.data_rights
)
triples = list(self.dataset.graph.triples(
(self.version_level_IRI, self.iri_version, None)))
self.assertTrue(len(triples) == 1,
"didn't get exactly one version level version triple")
self.assertEqual(triples[0][2],
Literal(self.data_release_version, datatype=XSD.date),
"version level version triple (set explicitly) is wrong ")
示例3: test_version_level_source_version_download_timestamp
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def test_version_level_source_version_download_timestamp(self):
path_to_dl_file = '/'.join(
(self.source.rawdir, self.source.files.get('test_file').get('file')))
fstat = os.stat(path_to_dl_file)
self.downloaded_file_timestamp = \
datetime.utcfromtimestamp(fstat[ST_CTIME]).strftime("%Y%m%d")
triples = list(self.source.dataset.graph.triples(
(URIRef(self.theseFiles.get("test_file").get("url")),
self.iri_retrieved_on,
None)))
self.assertTrue(len(triples) == 1,
"missing triple for ingest file retrieved on " +
"(download timestamp)")
self.assertEqual(Literal(triples[0][2], datatype=XSD.date),
Literal(self.downloaded_file_timestamp, datatype=XSD.date),
"version level source version timestamp isn't " +
"the same as the download timestamp of the local file")
示例4: test_postgres_version_level_source_version_download_timestamp
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def test_postgres_version_level_source_version_download_timestamp(self):
path_to_dl_file = '/'.join(
(self.pg_source.rawdir, self.pg_source.files.get('test_file').get('file')))
fstat = os.stat(path_to_dl_file)
self.downloaded_file_timestamp = \
datetime.utcfromtimestamp(fstat[ST_CTIME]).strftime("%Y%m%d")
triples = list(self.pg_source.dataset.graph.triples(
(URIRef(self.theseFiles.get("test_file").get("url")),
self.iri_retrieved_on,
None)))
self.assertTrue(len(triples) == 1,
"missing triple for ingest file retrieved on " +
"(download timestamp)")
self.assertEqual(Literal(triples[0][2], datatype=XSD.date),
Literal(self.downloaded_file_timestamp, datatype=XSD.date),
"version level source version timestamp isn't " +
"the same as the download timestamp of the local file")
示例5: parse_entity
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def parse_entity(self, term):
if isinstance(term, rdf.Literal):
return Entity(id=str(term), cls="_Literal")
elif isinstance(term, rdf.BNode):
return None
entstr = str(term)
if entstr.startswith(self.entity_prefix):
inst = entstr[len(self.entity_prefix):]
if self.d_entity.match(inst):
cls = 'd'
elif self.bond_entity.match(inst):
cls = 'bond'
else:
cls = None
return Entity(id=inst, cls=cls)
else:
return None
示例6: stringify_literal
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def stringify_literal(graph, node, ns_manager=None):
lit_val_string = str(node.value)
lex_val_string = str(node)
if ns_manager is None: # pragma: no cover
ns_manager = graph.namespace_manager
ns_manager.bind("sh", SH)
if lit_val_string != lex_val_string:
val_string = "\"{}\" = {}".format(lex_val_string, lit_val_string)
else:
val_string = "\"{}\"".format(lex_val_string)
if node.language:
lang_string = ", lang={}".format(str(node.language))
else:
lang_string = ""
if node.datatype:
datatype_uri = stringify_node(graph, node.datatype,
ns_manager=ns_manager)
datatype_string = ", datatype={}".format(datatype_uri)
else:
datatype_string = ""
node_string = "Literal({}{}{})" \
.format(val_string,
lang_string,
datatype_string)
return node_string
示例7: stringify_node
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [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
示例8: __init__
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def __init__(self, shape, rule_node):
"""
:param shape:
:type shape: Shape
:param rule_node:
:type rule_node: rdflib.Identifier
"""
super(SPARQLRule, self).__init__(shape, rule_node)
construct_nodes = set(self.shape.sg.objects(self.node, SH_construct))
if len(construct_nodes) < 1:
raise RuleLoadError("No sh:construct on SPARQLRule", "https://www.w3.org/TR/shacl-af/#SPARQLRule")
self._constructs = []
for c in construct_nodes:
if not isinstance(c, Literal) or not (c.datatype == XSD_string or c.language is not None or isinstance(c.value, str)):
raise RuleLoadError("SPARQLRule sh:construct must be an xsd:string", "https://www.w3.org/TR/shacl-af/#SPARQLRule")
self._constructs.append(str(c.value))
query_helper = SPARQLQueryHelper(self.shape, self.node, None, deactivated=self._deactivated)
query_helper.collect_prefixes()
self._qh = query_helper
示例9: get_nodes_from_node_expression
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def get_nodes_from_node_expression(self, expr, focus_node, data_graph):
if expr == SH_this:
return [focus_node]
elif isinstance(expr, (rdflib.URIRef, rdflib.Literal)):
return [expr]
elif isinstance(expr, rdflib.BNode):
path_nodes = set(self.shape.sg.objects(expr, SH_path))
if len(path_nodes) > 0:
path_results = []
for p in path_nodes:
vals = self.shape.value_nodes_from_path(self.shape.sg, focus_node, p, data_graph)
path_results.extend(vals)
return path_results
else:
raise NotImplementedError("Unsupported expression s, p, or o, in SHACL TripleRule")
else:
raise NotImplementedError("Unsupported expression s, p, or o, in SHACL TripleRule")
示例10: __init__
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def __init__(self, shacl_graph, node, *args, **kwargs):
super(AskConstraintValidator, self).__init__(shacl_graph, node, **kwargs)
g = shacl_graph.graph
ask_vals = set(g.objects(node, SH_ask))
if len(ask_vals) < 1 or len(ask_vals) > 1:
# TODO:coverage: No test for this case
raise ConstraintLoadError(
"AskValidator must have exactly one value for sh:ask.",
"https://www.w3.org/TR/shacl/#ConstraintComponent")
ask_val = next(iter(ask_vals))
if not (isinstance(ask_val, rdflib.Literal) and
isinstance(ask_val.value, str)):
# TODO:coverage: No test for this case
raise ConstraintLoadError(
"AskValidator sh:ask must be an RDF Literal of type xsd:string.",
"https://www.w3.org/TR/shacl/#ConstraintComponent")
self.query_text = ask_val.value
示例11: _evaluate_string_rule
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def _evaluate_string_rule(self, r, target_graph, f_v_dict):
reports = []
non_conformant = False
assert isinstance(r, rdflib.Literal)
min_len = int(r.value)
if min_len < 0:
raise ReportableRuntimeError("Minimum length cannot be less than zero!")
for f, value_nodes in f_v_dict.items():
for v in value_nodes:
flag = False
if min_len == 0:
flag = True # min len zero always passes
elif isinstance(v, rdflib.BNode):
# blank nodes cannot pass minLen validation
pass
else:
v_string = self.value_node_to_string(v)
flag = len(v_string) >= min_len
if not flag:
non_conformant = True
rept = self.make_v_result(target_graph, f, value_node=v)
reports.append(rept)
return non_conformant, reports
示例12: __init__
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def __init__(self, shape):
super(UniqueLangConstraintComponent, self).__init__(shape)
self.allow_multi_rules = False
is_unique_lang = set(self.shape.objects(SH_uniqueLang))
if len(is_unique_lang) < 1:
raise ConstraintLoadError(
"UniqueLangConstraintComponent must have at least one sh:uniqueLang predicate.",
"https://www.w3.org/TR/shacl/#UniqueLangConstraintComponent")
elif len(is_unique_lang) > 1:
raise ConstraintLoadError(
"UniqueLangConstraintComponent must have at most one sh:uniqueLang predicate.",
"https://www.w3.org/TR/shacl/#UniqueLangConstraintComponent")
if not shape.is_property_shape:
raise ConstraintLoadError(
"UniqueLangConstraintComponent can only be present on a PropertyShape, not a NodeShape.",
"https://www.w3.org/TR/shacl/#UniqueLangConstraintComponent")
is_unique_lang = next(iter(is_unique_lang))
try:
assert isinstance(is_unique_lang, rdflib.Literal)
assert isinstance(is_unique_lang.value, bool)
except (AssertionError, AttributeError):
raise ConstraintLoadError(
"UniqueLangConstraintComponent must have an RDF Literal of type boolean as its sh:uniqueLang.",
"https://www.w3.org/TR/shacl/#UniqueLangConstraintComponent")
self.string_rules = {is_unique_lang.value}
示例13: evaluate
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def evaluate(self, target_graph, focus_value_nodes, _evaluation_path):
"""
:type focus_value_nodes: dict
:type target_graph: rdflib.Graph
"""
reports = []
non_conformant = False
for lt in iter(self.property_compare_set):
if isinstance(lt, rdflib.Literal) or\
isinstance(lt, rdflib.BNode):
raise ReportableRuntimeError(
"Value of sh:lessThan MUST be a URI Identifier.")
_nc, _r = self._evaluate_less_than(lt, target_graph, focus_value_nodes)
non_conformant = non_conformant or _nc
reports.extend(_r)
return (not non_conformant), reports
示例14: __init__
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def __init__(self, shape):
super(ClosedConstraintComponent, self).__init__(shape)
sg = self.shape.sg.graph
closed_vals = list(self.shape.objects(SH_closed))
if len(closed_vals) < 1:
raise ConstraintLoadError(
"ClosedConstraintComponent must have at least one sh:closed predicate.",
"https://www.w3.org/TR/shacl/#ClosedConstraintComponent")
elif len(closed_vals) > 1:
raise ConstraintLoadError(
"ClosedConstraintComponent must have at most one sh:closed predicate.",
"https://www.w3.org/TR/shacl/#ClosedConstraintComponent")
assert isinstance(closed_vals[0], rdflib.Literal), "sh:closed must take a xsd:boolean literal."
self.is_closed = bool(closed_vals[0].value)
ignored_vals = list(self.shape.objects(SH_ignoredProperties))
self.ignored_props = set()
for i in ignored_vals:
try:
items = set(sg.items(i))
for list_item in items:
self.ignored_props.add(list_item)
except ValueError:
continue
self.property_shapes = list(self.shape.objects(SH_property))
示例15: init_prov_graph
# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import Literal [as 别名]
def init_prov_graph(self):
"""
Initialize PROV graph with all we know at the start of the recording
"""
try:
# Use git2prov to get prov on the repo
repo_prov = check_output(
['node_modules/git2prov/bin/git2prov', 'https://github.com/{}/{}/'.format(self.user, self.repo),
'PROV-O']).decode("utf-8")
repo_prov = repo_prov[repo_prov.find('@'):]
# glogger.debug('Git2PROV output: {}'.format(repo_prov))
glogger.debug('Ingesting Git2PROV output into RDF graph')
with open('temp.prov.ttl', 'w') as temp_prov:
temp_prov.write(repo_prov)
self.prov_g.parse('temp.prov.ttl', format='turtle')
except Exception as e:
glogger.error(e)
glogger.error("Couldn't parse Git2PROV graph, continuing without repo PROV")
pass
self.prov_g.add((self.agent, RDF.type, self.prov.Agent))
self.prov_g.add((self.entity_d, RDF.type, self.prov.Entity))
self.prov_g.add((self.activity, RDF.type, self.prov.Activity))
# entity_d
self.prov_g.add((self.entity_d, self.prov.wasGeneratedBy, self.activity))
self.prov_g.add((self.entity_d, self.prov.wasAttributedTo, self.agent))
# later: entity_d genereated at time (when we know the end time)
# activity
self.prov_g.add((self.activity, self.prov.wasAssociatedWith, self.agent))
self.prov_g.add((self.activity, self.prov.startedAtTime, Literal(datetime.now())))
# later: activity used entity_o_1 ... entity_o_n
# later: activity endedAtTime (when we know the end time)