当前位置: 首页>>代码示例>>Python>>正文


Python rdflib.URIRef方法代码示例

本文整理汇总了Python中rdflib.URIRef方法的典型用法代码示例。如果您正苦于以下问题:Python rdflib.URIRef方法的具体用法?Python rdflib.URIRef怎么用?Python rdflib.URIRef使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rdflib的用法示例。


在下文中一共展示了rdflib.URIRef方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [as 别名]
def __init__(self, user, repo):
        """Default constructor.

        Keyword arguments:
        user -- Github user.
        repo -- Github repo.
        """
        self.user = user
        self.repo = repo
        self.prov_g = Graph()
        prov_uri = URIRef("http://www.w3.org/ns/prov#")
        self.prov = Namespace(prov_uri)
        self.prov_g.bind('prov', self.prov)

        self.agent = URIRef("http://{}".format(static.SERVER_NAME))
        self.entity_d = URIRef("http://{}/api/{}/{}/spec".format(static.SERVER_NAME, self.user, self.repo))
        self.activity = URIRef(self.entity_d + "-activity")

        self.init_prov_graph() 
开发者ID:CLARIAH,项目名称:grlc,代码行数:21,代码来源:prov.py

示例2: to_rdf

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [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 
开发者ID:archesproject,项目名称:arches,代码行数:26,代码来源:datatypes.py

示例3: test_rdf_concept_list

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [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) 
开发者ID:archesproject,项目名称:arches,代码行数:25,代码来源:datatype_to_rdf_tests.py

示例4: test_version_level_source_version_download_timestamp

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [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") 
开发者ID:monarch-initiative,项目名称:dipper,代码行数:21,代码来源:test_source_metadata.py

示例5: hpo_to_tree

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [as 别名]
def hpo_to_tree(cls, hpo_terms, hpo_graph, tree, path):
    tree_path = copy.copy(path)
    tree_path.append(cls)
    curie_util = CurieUtil(curie_map.get())
    if cls not in hpo_terms:
        hpo_terms[cls] = {
            'label': hpo_graph.label(URIRef(curie_util.get_uri(cls)))
        }
        parents = hpo_graph.objects(URIRef(curie_util.get_uri(cls)), RDFS.subClassOf)
        hpo_terms[cls]['parents'] = len(list(parents))

        lay_person = get_lay_person(cls, hpo_graph)
        hpo_terms[cls]["lay_person"] = lay_person

    # Traverse the tree to get to the input class
    position = tree[tree_path[0]]
    for term in tree_path[1:]:
        position = position[term]

    for sub_class in hpo_graph.subjects(RDFS.subClassOf, URIRef(curie_util.get_uri(tree_path[-1]))):
        curie = curie_util.get_curie(sub_class).replace("OBO:HP_", "HP:")
        position[curie] = {}
        hpo_to_tree(curie, hpo_terms, hpo_graph, tree, tree_path) 
开发者ID:monarch-initiative,项目名称:dipper,代码行数:25,代码来源:treeify-hpo.py

示例6: stringify_node

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [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 
开发者ID:RDFLib,项目名称:pySHACL,代码行数:21,代码来源:stringify.py

示例7: get_nodes_from_node_expression

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [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") 
开发者ID:RDFLib,项目名称:pySHACL,代码行数:19,代码来源:__init__.py

示例8: html_elem

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [as 别名]
def html_elem(e, ct, withtype=False):
    """
    Format a result element as an HTML table cell.
      @param e (list): a pair \c (value,type)
      @param ct (str): cell type (th or td)
      @param withtype (bool): add an additional cell with the element type
    """
    # Header cell
    if ct == 'th':
        return '<th>{0}</th><th>{1}</th>'.format(*e) if withtype else '<th>{}</th>'.format(e)
    # Content cell
    if e[1] in ('uri', 'URIRef'):
        html = u'<{0} class=val><a href="{1}" target="_other">{2}</a></{0}>'.format(ct, e[0], escape(e[0]))
    else:
        html = u'<{0} class=val>{1}</{0}>'.format(ct, escape(e[0]))
    # Create the optional cell for the type
    if withtype:
        html += u'<{0} class=typ>{1}</{0}>'.format(ct, e[1])
    return html 
开发者ID:paulovn,项目名称:sparql-kernel,代码行数:21,代码来源:connection.py

示例9: _ExpandFootnotes

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [as 别名]
def _ExpandFootnotes(self):
    for result in self.graph.query(
        MakeSparqlSelectQuery(
            ('?ds', 'a', 'schema:StatisticalDataset'),
            ('?ds', 'schema:footnote', '?fn'),
            ns_manager=self.graph.namespace_manager)):
      if result['fn'] not in self.subjects:
        self.graph.remove((result['ds'], SCHEMA.footnote, result['fn']))
        id_prefix = urldefrag(str(result['ds'])).url
        with self.getter.Fetch(str(result['fn'])) as f:
          reader = DictReader(f)
          for row in reader:
            row_id = rdflib.URIRef(id_prefix + '#footnote=' + row['codeValue'])
            self.graph.add((result['ds'], SCHEMA.footnote, row_id))
            self.graph.add((row_id, rdflib.RDF.type,
                            SCHEMA.StatisticalAnnotation))
            for key, val in row.items():
              fields = key.split('@')
              if len(fields) > 1:
                # A language code is specified
                self.graph.add((row_id, getattr(SCHEMA, fields[0]),
                                rdflib.Literal(val, language=fields[1])))
              else:
                self.graph.add((row_id, getattr(SCHEMA, key),
                                rdflib.Literal(val))) 
开发者ID:google,项目名称:dspl,代码行数:27,代码来源:expander.py

示例10: _ExpandSliceData

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [as 别名]
def _ExpandSliceData(self, slice_id):
    tableMappings = self._GetTableMappings(slice_id)
    dim_data = self._GetDimensionDataForSlice(slice_id, tableMappings)
    measure_data = self._GetMeasureDataForSlice(slice_id, tableMappings)
    for data_id in self.graph.objects(
        subject=slice_id,
        predicate=SCHEMA.data):
      if data_id not in self.subjects:
        with self.getter.Fetch(data_id) as f:
          reader = DictReader(f)
          try:
            for row in reader:
              row_id = rdflib.URIRef(self._MakeSliceDataRowId(
                  slice_id, dim_data, measure_data, row, tableMappings))
              self.graph.add((slice_id, SCHEMA.data, row_id))
              self.graph.add((row_id, rdflib.RDF.type, SCHEMA.Observation))
              self.graph.add((row_id, SCHEMA.slice, slice_id))
              for dim, data in dim_data.items():
                self._ExpandObservationDimensionValue(dim, data, row_id, row)
              for measure, data in measure_data.items():
                self._ExpandObservationMeasureValue(measure, data, row_id, row)
          except Exception as e:
            raise RuntimeError(f"Error processing {data_id} at line {reader.line_num}") from e 
开发者ID:google,项目名称:dspl,代码行数:25,代码来源:expander.py

示例11: _object_value_int

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [as 别名]
def _object_value_int(self, subject, predicate):
        '''
        Given a subject and a predicate, returns the value of the object as an
        integer

        Both subject and predicate must be rdflib URIRef or BNode objects

        If the value can not be parsed as intger, returns None
        '''
        object_value = self._object_value(subject, predicate)
        if object_value:
            try:
                return int(object_value)
            except ValueError:
                pass
        return None 
开发者ID:italia,项目名称:daf-recipes,代码行数:18,代码来源:profiles.py

示例12: _contact_details

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [as 别名]
def _contact_details(self, subject, predicate):
        '''
        Returns a dict with details about a vcard expression

        Both subject and predicate must be rdflib URIRef or BNode objects

        Returns keys for uri, name and email with the values set to
        None if they could not be found
        '''

        contact = {}

        for agent in self.g.objects(subject, predicate):

            contact['uri'] = (unicode(agent) if isinstance(agent,
                              rdflib.term.URIRef) else None)

            contact['name'] = self._object_value(agent, VCARD.fn)

            contact['email'] = self._object_value(agent, VCARD.hasEmail)

        return contact 
开发者ID:italia,项目名称:daf-recipes,代码行数:24,代码来源:profiles.py

示例13: test_dataset_license_from_distribution_by_title

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [as 别名]
def test_dataset_license_from_distribution_by_title(self):
        # license_id retrieved from dct:title of dcat:license object
        g = Graph()

        dataset = URIRef("http://example.org/datasets/1")
        g.add((dataset, RDF.type, DCAT.Dataset))

        distribution = URIRef("http://example.org/datasets/1/ds/1")
        g.add((distribution, RDF.type, DCAT.Distribution))
        g.add((dataset, DCAT.distribution, distribution))
        license = BNode()
        g.add((distribution, DCT.license, license))
        g.add((license, DCT.title, Literal("Creative Commons Attribution")))

        p = RDFParser(profiles=['euro_dcat_ap'])

        p.g = g

        dataset = [d for d in p.datasets()][0]
        eq_(dataset['license_id'], 'cc-by') 
开发者ID:italia,项目名称:daf-recipes,代码行数:22,代码来源:test_euro_dcatap_profile_parse.py

示例14: test_distribution_access_url

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [as 别名]
def test_distribution_access_url(self):
        g = Graph()

        dataset1 = URIRef("http://example.org/datasets/1")
        g.add((dataset1, RDF.type, DCAT.Dataset))

        distribution1_1 = URIRef("http://example.org/datasets/1/ds/1")
        g.add((distribution1_1, RDF.type, DCAT.Distribution))
        g.add((distribution1_1, DCAT.accessURL, Literal('http://access.url.org')))
        g.add((dataset1, DCAT.distribution, distribution1_1))

        p = RDFParser(profiles=['euro_dcat_ap'])

        p.g = g

        datasets = [d for d in p.datasets()]

        resource = datasets[0]['resources'][0]

        eq_(resource['url'], u'http://access.url.org')
        assert 'download_url' not in resource 
开发者ID:italia,项目名称:daf-recipes,代码行数:23,代码来源:test_euro_dcatap_profile_parse.py

示例15: test_distribution_download_url

# 需要导入模块: import rdflib [as 别名]
# 或者: from rdflib import URIRef [as 别名]
def test_distribution_download_url(self):
        g = Graph()

        dataset1 = URIRef("http://example.org/datasets/1")
        g.add((dataset1, RDF.type, DCAT.Dataset))

        distribution1_1 = URIRef("http://example.org/datasets/1/ds/1")
        g.add((distribution1_1, RDF.type, DCAT.Distribution))
        g.add((distribution1_1, DCAT.downloadURL, Literal('http://download.url.org')))
        g.add((dataset1, DCAT.distribution, distribution1_1))

        p = RDFParser(profiles=['euro_dcat_ap'])

        p.g = g

        datasets = [d for d in p.datasets()]

        resource = datasets[0]['resources'][0]

        eq_(resource['url'], u'http://download.url.org')
        eq_(resource['download_url'], u'http://download.url.org') 
开发者ID:italia,项目名称:daf-recipes,代码行数:23,代码来源:test_euro_dcatap_profile_parse.py


注:本文中的rdflib.URIRef方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。