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


Python Graph.remove方法代码示例

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


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

示例1: TestAuditableStoreEmbeded

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
class TestAuditableStoreEmbeded(BaseTestAuditableStore):

    def setUp(self):
        self.g = Graph()
        self.g.add((EX.s0, EX.p0, EX.o0))
        self.g.add((EX.s0, EX.p0, EX.o0bis))

        self.t1 = Graph(AuditableStore(self.g.store),
                        self.g.identifier)
        self.t1.add((EX.s1, EX.p1, EX.o1))
        self.t1.remove((EX.s0, EX.p0, EX.o0bis))

        self.t2 = Graph(AuditableStore(self.t1.store),
                        self.t1.identifier)
        self.t2.add((EX.s2, EX.p2, EX.o2))
        self.t2.remove((EX.s1, EX.p1, EX.o1))

    def test_commit_commit(self):
        self.assert_graph_equal(self.t2, [
            (EX.s0, EX.p0, EX.o0),
            (EX.s2, EX.p2, EX.o2),
        ])
        self.t2.commit()
        self.assert_graph_equal(self.t1, [
            (EX.s0, EX.p0, EX.o0),
            (EX.s2, EX.p2, EX.o2),
        ])
        self.t1.commit()
        self.assert_graph_equal(self.g, [
            (EX.s0, EX.p0, EX.o0),
            (EX.s2, EX.p2, EX.o2),
        ])

    def test_commit_rollback(self):
        self.t2.commit()
        self.t1.rollback()
        self.assert_graph_equal(self.g, [
            (EX.s0, EX.p0, EX.o0),
            (EX.s0, EX.p0, EX.o0bis),
        ])

    def test_rollback_commit(self):
        self.t2.rollback()
        self.assert_graph_equal(self.t1, [
            (EX.s0, EX.p0, EX.o0),
            (EX.s1, EX.p1, EX.o1),
        ])
        self.t1.commit()
        self.assert_graph_equal(self.g, [
            (EX.s0, EX.p0, EX.o0),
            (EX.s1, EX.p1, EX.o1),
        ])

    def test_rollback_rollback(self):
        self.t2.rollback()
        self.t1.rollback()
        self.assert_graph_equal(self.g, [
            (EX.s0, EX.p0, EX.o0),
            (EX.s0, EX.p0, EX.o0bis),
        ])
开发者ID:Dataliberate,项目名称:rdflib,代码行数:62,代码来源:test_auditable.py

示例2: convert_graveyards

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
    def convert_graveyards(self, uri, graph: Graph):
        """
        Convert graveyard information into URIs. Check if the created URI exists in cemeteries ontology.
        """
        mun = graph.value(uri, SCHEMA_CAS.municipality_of_burial)
        if not mun or str(mun) == 'X':
            return graph

        gy = graph.value(uri, SCHEMA_CAS.graveyard_number)
        gy_uri = '{base}h{mun}'.format(base=CEMETERIES, mun=str(mun).split('/k')[-1])
        # mun_uri = '{base}k{mun}'.format(base=KUNNAT, mun=mun)
        if gy:
            gy_uri += '_{gy}'.format(gy=gy)
        else:
            return graph

        gy_uri = URIRef(GRAVEYARD_MAPPING.get(gy_uri, gy_uri))

        if gy_uri not in self.cemeteries:
            logging.info('Cemetery {gy} not found for person {p}'.format(gy=gy_uri, p=uri))
            return graph

        if str(gy).isnumeric():
            graph.add((uri, SCHEMA_WARSA.buried_in, gy_uri))

        graph.remove((uri, SCHEMA_CAS.graveyard_number, gy))

        return graph
开发者ID:SemanticComputing,项目名称:Casualty-linking,代码行数:30,代码来源:csv_to_rdf.py

示例3: makerdf

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
def makerdf(workflow, wf, ctx):
    # type: (Union[str, unicode], Union[List[Dict[unicode, Any]], Dict[unicode, Any]], Loader.ContextType) -> Graph
    prefixes = {}
    for k,v in ctx.iteritems():
        if isinstance(v, dict):
            url = v["@id"]
        else:
            url = v
        doc_url, frg = urlparse.urldefrag(url)
        if "/" in frg:
            p, _ = frg.split("/")
            prefixes[p] = u"%s#%s/" % (doc_url, p)

    if isinstance(wf, list):
        for entry in wf:
            entry["@context"] = ctx
    else:
        wf["@context"] = ctx
    g = Graph().parse(data=json.dumps(wf), format='json-ld', location=workflow)

    # Bug in json-ld loader causes @id fields to be added to the graph
    for s,p,o in g.triples((None, URIRef("@id"), None)):
        g.remove((s, p, o))

    for k2,v2 in prefixes.iteritems():
        g.namespace_manager.bind(k2, v2)

    return g
开发者ID:curoverse,项目名称:cwltool,代码行数:30,代码来源:cwlrdf.py

示例4: link_municipalities

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
def link_municipalities(municipalities: Graph, warsa_endpoint: str, arpa_endpoint: str):
    """
    Link to Warsa municipalities.
    """
    warsa_munics = r.helpers.read_graph_from_sparql(warsa_endpoint,
                                                    graph_name='http://ldf.fi/warsa/places/municipalities')

    log.info('Using Warsa municipalities with {n} triples'.format(n=len(warsa_munics)))

    municipalities.remove((None, SCHEMA_CAS.current_municipality, None))
    municipalities.remove((None, SCHEMA_CAS.wartime_municipality, None))

    pnr_arpa = Arpa(arpa_endpoint)
    municipalities = link_to_pnr(municipalities, SCHEMA_CAS.current_municipality, None, pnr_arpa)['graph']

    for casualty_munic in list(municipalities[:RDF.type:SCHEMA_CAS.Municipality]):
        labels = list(municipalities[casualty_munic:SKOS.prefLabel:])

        warsa_match = link_warsa_municipality(warsa_munics, labels)
        if warsa_match:
            municipalities.add((casualty_munic, SCHEMA_CAS.wartime_municipality, warsa_match))

        preferred = warsa_match or \
                    municipalities.value(casualty_munic, SCHEMA_CAS.current_municipality) or \
                    casualty_munic
        if preferred:
            municipalities.add((casualty_munic, SCHEMA_CAS.preferred_municipality, preferred))

    return municipalities
开发者ID:SemanticComputing,项目名称:Casualty-linking,代码行数:31,代码来源:linker.py

示例5: remove_handle

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
    def remove_handle(self, key):

        dir_ = self._key2filename(key)

        # remove handle from collection descriptor:
        uri = Graph().parse(opj(self.path, dir_, REPO_STD_META_FILE),
                            format="turtle").value(predicate=RDF.type,
                                                   object=DLNS.Handle)
        col_graph = Graph().parse(opj(self.path, REPO_STD_META_FILE),
                                  format="turtle")
        col_graph.remove((DLNS.this, DCTERMS.hasPart, uri))
        col_graph.serialize(opj(self.path, REPO_STD_META_FILE), format="turtle")

        # remove handle's directory:
        # Note: Currently all files separatly due to issues with the
        # normalize_path decorator in gitrepo.py. It expects one output per
        # one input file. So, recursively removing the 'dir_' violates that
        # assertion.
        # Note2: Currently using "-f" option, since on ntfs/vfat, git somehow
        # reports the files (at least config.ttl) have staged changes.
        # TODO: Figure out, what the hell this is about.
        [self.git_remove(file_, f=True) for file_ in self.get_indexed_files()
         if file_.startswith(dir_)]

        self.git_add(REPO_STD_META_FILE)
        self.git_commit("Removed handle %s." % key)
开发者ID:WurstWorks,项目名称:datalad,代码行数:28,代码来源:collectionrepo.py

示例6: test_post_illegal_rdf

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
 def test_post_illegal_rdf(self):
     # try to post a graph without an rdf:type for the created element
     graph = Graph()
     graph.parse(data=POSTABLE_TURTLE, publicID=URL, format="n3")
     created = next(graph.triples((URIRef(URL), None, None)))[2]
     graph.remove((created, RDF.type, None))
     new_content = graph.serialize(format="nt")
     reqhead = { "content-type": "text/nt" }
     resp, content = self.request(URL, "POST", new_content, reqhead)
     eq_(resp.status_int, 403)
开发者ID:fderbel,项目名称:ktbs,代码行数:12,代码来源:test_rdfrest_http_server.py

示例7: download_from_atom

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
    def download_from_atom(self):
        refresh = self.config.force
        feed_url = self.start_url
        ns = 'http://www.w3.org/2005/Atom'
        done = False
        biggraph = Graph()
        biggraph.bind("dct", self.ns['dct'])
        biggraph.bind("rpubl", self.ns['rpubl'])

        while not done:
            self.log.info("Feed: %s" % feed_url)
            tree = etree.parse(requests.get(feed_url).text)
            for entry in tree.findall('{%s}entry' % (ns)):
                try:
                    self.log.info("  Examining entry")
                    rdf_url = None
                    for node in entry:
                        if (node.tag == "{%s}link" % ns and
                                node.get('type') == 'application/rdf+xml'):
                            rdf_url = urljoin(feed_url, node.get("href"))
                        elif (node.tag == "{%s}content" % ns and
                              node.get('type') == 'application/rdf+xml'):
                            rdf_url = urljoin(feed_url, node.get("src"))

                    if rdf_url:
                        self.log.info("    RDF: %s" % rdf_url)
                        g = Graph()
                        g.parse(requests.get(rdf_url).text)
                        for triple in g:
                            s, p, o = triple
                            if (not isinstance(o, URIRef) or
                                    not str(o).startswith(self.config.url)):
                                g.remove(triple)

                        self.log.debug("     Adding %s triples" % len(g))
                        biggraph += g
                except KeyboardInterrupt:
                    raise
                except:
                    e = sys.exc_info()[1]
                    self.log.error("ERROR: %s" % e)

            done = True
            for link in list(tree.findall('{%s}link' % (ns))):
                self.log.info("  Examining link")
                if link.get('rel') == 'prev-archive':
                    feed_url = urljoin(feed_url, link.get("href"))
                    done = False
                    # done = True

        self.log.info("Done downloading")
        with self.store.open_downloaded("biggraph", "wb") as fp:
            fp.write(biggraph.serialize(format="nt"))
开发者ID:h4ck3rm1k3,项目名称:ferenda,代码行数:55,代码来源:skeleton.py

示例8: update_graph_with_proxy_field

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
    def update_graph_with_proxy_field(self, graph: Graph, proxy_field_uri: str):
        """# return graph, tuple_list with coined_uris, label, lang."""
        property_uri = URIRef(proxy_field_uri)
        fields = graph.subject_objects(predicate=property_uri)
        converted_literals = []
        for subject, obj in fields:
            if isinstance(obj, Literal):
                graph.remove((subject, property_uri, obj))
                new_uri = self.generate_proxyfield_uri(obj.value, obj.language)
                graph.add((subject, property_uri, URIRef(new_uri)))
                converted_literals.append((new_uri, obj))

        return graph, converted_literals
开发者ID:delving,项目名称:nave,代码行数:15,代码来源:models.py

示例9: remove_canvas_triples

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
def remove_canvas_triples(project_uri, canvas_uri, input_graph):
    project_graph = Graph(store=rdfstore(), identifier=canvas_identifier)
    project_metadata_g = Graph(rdfstore(), identifier=uris.project_metadata_graph_identifier(project_uri))

    removed_graph = Graph()

    for t in input_graph:
        if t in project_graph:
            project_graph.remove(t)
            project_metadata_g.remove(t)
            removed_graph.add(t)

    return removed_graph
开发者ID:bobclewell,项目名称:DM,代码行数:15,代码来源:canvases.py

示例10: _edit_untrusted

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
    def _edit_untrusted(self, parameters, clear):
        """I implement :meth:`edit` in the case it is untrusted.
        """
        if self._edit_context:
            raise RdfRestException("Can not embed untrusted edit context")
        prepared = self.prepare_edit(parameters)
        self._edit_context = (False, parameters, prepared)
        if self._graph.store.transaction_aware:
            editable = self._graph
        else:
            editable = Graph(identifier=self.uri)
            if not clear:
                editable_add = editable.add
                for triple in self._graph: 
                    editable_add(triple)

        with self.service:
            try:
                if clear and editable is self._graph:
                    editable.remove((None, None, None))
                yield editable
                self.complete_new_graph(self.service, self.uri, parameters,
                                        editable, self)
                diag = self.check_new_graph(self.service, self.uri, parameters,
                                            editable, self)
                if not diag:
                    raise InvalidDataError(unicode(diag))

                if not editable is self._graph:
                    # we replace self._graph by editable
                    # We assume that
                    # * most triples between the two graphs are the same
                    # * testing that a graph contains a triple is less
                    #   costly than adding it or removing it (which involves
                    #   updating several indexes -- this is verified by
                    #   IOMemory, and roughly so by Sleepycat)
                    # so the following should more efficient than simply
                    # emptying self_graph and then filling it with
                    # editable_graph
                    g = self._graph
                    g_remove = g.remove
                    e_contains = editable.__contains__
                    for triple in g:
                        if not e_contains(triple):
                            g_remove(triple)
                    g.addN( (s, p, o, g) for s, p, o in editable )
                # alter _edit_context so that ack_edit can embed an edit ctxt:
                self._edit_context = (True, parameters)
                self.ack_edit(parameters, prepared)
            finally:
                self._edit_context = None
开发者ID:,项目名称:,代码行数:53,代码来源:

示例11: investigate_len_issue

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
def investigate_len_issue():
    import shutil, commands
    store = plugin.get('SQLAlchemy', Store)(
        identifier=URIRef("rdflib_test"),
        configuration=Literal("sqlite:///%(here)s/development.sqlite" % {
                                                        "here": os.getcwd()}))
    g0 = Graph('Sleepycat')
    g0.open('/tmp/foo', create=True)
    print("Len g0 on opening: %s\n" % len(g0))
    g1 = Graph(store)
    print("Len g1 on opening: %s\n" % len(g1))
    statementId = BNode()
    print("Adding %s\n\t%s\n\t%s\n" % (statementId, RDF.type, RDF.Statement))
    g0.add((statementId, RDF.type, RDF.Statement))
    g1.add((statementId, RDF.type, RDF.Statement))
    print("Adding %s\n\t%s\n\t%s\n" % (statementId, RDF.subject,
           URIRef(u'http://rdflib.net/store/ConjunctiveGraph')))
    g0.add((statementId, RDF.subject,
           URIRef(u'http://rdflib.net/store/ConjunctiveGraph')))
    g1.add((statementId, RDF.subject,
           URIRef(u'http://rdflib.net/store/ConjunctiveGraph')))
    print("Adding %s\n\t%s\n\t%s\n" % (statementId, RDF.predicate, RDFS.label))
    g0.add((statementId, RDF.predicate, RDFS.label))
    g1.add((statementId, RDF.predicate, RDFS.label))
    print("Adding %s\n\t%s\n\t%s\n" % (
        statementId, RDF.object, Literal("Conjunctive Graph")))
    g0.add((statementId, RDF.object, Literal("Conjunctive Graph")))
    print("Len g0 after adding 4 triples %s\n" % len(g0))
    g1.add((statementId, RDF.object, Literal("Conjunctive Graph")))
    print("Len g1 after adding 4 triples %s\n" % len(g1))
    print(g0.serialize(format="nt") + "\n")
    for s, p, o in g0:
        print("s = %s\n\tp = %s\n\to = %s\n" % (
            repr(s), repr(p), repr(o)))
    print(g1.serialize(format="nt") + "\n")
    for s, p, o in g1:
        print("s = %s\n\tp = %s\n\to = %s\n" % (
            repr(s), repr(p), repr(o)))
    commands.getoutput('cp development.sqlite devcopy.sqlite')
    print("Removing %s\n\t%s\n\t%s\n" % (statementId, RDF.type, RDF.Statement))
    g0.remove((statementId, RDF.type, RDF.Statement))
    print("Len g0 after removal %s\n" % len(g0))
    g1.remove((statementId, RDF.type, RDF.Statement))
    print("Len g1 after removal %s\n" % len(g1))
    print(g0.serialize(format="nt") + "\n")
    print(g1.serialize(format="nt") + "\n")
    g0.close()
    shutil.rmtree('/tmp/foo')
    g1.close()
    os.unlink("%(here)s/development.sqlite" % {"here": os.getcwd()})
开发者ID:IRI-Research,项目名称:rdflib-sqlalchemy,代码行数:52,代码来源:test.py

示例12: removeFromGraph

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
def removeFromGraph(timestamp, graphURI = "http://example.com/g1", db_conf={"dbname" : "postgres", "user" : "postgres", "password" : "admin" }):
    configString = ("dbname=postgres user=waccess password=write")
    #configString = ("dbname=" + db_conf['dbname'] + "user="+ db_conf['user'] + " password=" + db_conf['password'])
    graph = Graph('PostgreSQL', identifier=URIRef(graphURI))
    graph.open(configString, create=False)
    results = graph.query(queries.getEvents(timestamp))

    print len(results)
    for result in results:
        for node in result:
            graph.remove((node, None, None))

    # Commit and close the graph
    graph.commit()
    graph.close()
开发者ID:nikha1,项目名称:nyc-taxi,代码行数:17,代码来源:postgresInterface.py

示例13: test_put_illegal_rdf

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
 def test_put_illegal_rdf(self):
     # try to put a graph without any rdf:type for the resource
     reqhead = { "accept": "text/nt" }
     resp_get, content_get = self.request(URL, headers=reqhead)
     graph = Graph()
     graph.parse(data=content_get, publicID=URL, format="nt")
     graph.remove((URIRef(URL), RDF.type, None))
     new_content = graph.serialize(format="nt")
     assert resp_get.etag is not None
     reqhead = {
         "if-match": resp_get.etag,
         "content-type": "text/nt",
         }
     resp_put, content_put = self.request(URL, "PUT", new_content,
                                                   reqhead)
     eq_(resp_put.status_int, 403)
开发者ID:fderbel,项目名称:ktbs,代码行数:18,代码来源:test_rdfrest_http_server.py

示例14: makerdf

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
def makerdf(workflow,       # type: Text
            wf,             # type: Union[List[Dict[Text, Any]], Dict[Text, Any]]
            ctx,            # type: ContextType
            graph=None      # type: Graph
            ):
    # type: (...) -> Graph
    prefixes = {}
    idfields = []
    for k, v in six.iteritems(ctx):
        if isinstance(v, dict):
            url = v["@id"]
        else:
            url = v
        if url == "@id":
            idfields.append(k)
        doc_url, frg = urllib.parse.urldefrag(url)
        if "/" in frg:
            p = frg.split("/")[0]
            prefixes[p] = u"%s#%s/" % (doc_url, p)

    fix_jsonld_ids(wf, idfields)

    if graph is None:
        g = Graph()
    else:
        g = graph

    if isinstance(wf, list):
        for w in wf:
            w["@context"] = ctx
            g.parse(data=json.dumps(w), format='json-ld', publicID=str(workflow))
    else:
        wf["@context"] = ctx
        g.parse(data=json.dumps(wf), format='json-ld', publicID=str(workflow))

    # Bug in json-ld loader causes @id fields to be added to the graph
    for sub, pred, obj in g.triples((None, URIRef("@id"), None)):
        g.remove((sub, pred, obj))

    for k2, v2 in six.iteritems(prefixes):
        g.namespace_manager.bind(k2, v2)

    return g
开发者ID:denis-yuen,项目名称:cwltool,代码行数:45,代码来源:jsonld_context.py

示例15: add_utensil_actions

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import remove [as 别名]
def add_utensil_actions():
    """ Ajouter des actions à un ustensile """
    NS1 = Namespace('http://www.random-food.com/ontology#')
    store_file = STORE['utensils']
    dataj = json.loads(request.data)
    
    g = Graph()
    load_rdf_file(store_file, g)
    for s, p ,o in g.triples((None, RDF.type, NS1.Utensil)):
        if s.__str__() == dataj["utensil"]:
            print s
            for a, b, c in g.triples((s, NS1.Action,None)):
                print "remove"
                g.remove((a, b, c))

            for action in dataj["actions"]:
                g.add((s, NS1.Action, URIRef(action['uri'])))
    save_rdf_file(STORE['utensils'], g) 

    return jsonify({'uri': "test"})
开发者ID:poulp,项目名称:randomfoOd,代码行数:22,代码来源:routes.py


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