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


Python Graph.add方法代码示例

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


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

示例1: test_cax_dw

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [as 别名]
def test_cax_dw():
    """
    Test cax-dw rule for OWL 2 RL.

    If::

        T(?c1, owl:disjointWith, ?c2)
        T(?x, rdf:type, ?c1)
        T(?x, rdf:type, ?c2)

    then::

        false
    """
    g = Graph()

    x = T.x
    c1 = T.c1
    c2 = T.c2

    g.add((c1, OWL.disjointWith, c2))
    g.add((x, RDF.type, c1))
    g.add((x, RDF.type, c2))

    owlrl.DeductiveClosure(owlrl.OWLRL_Semantics).expand(g)

    result = next(g.objects(predicate=DAML.error))
    expected = Literal(
        'Disjoint classes http://test.org/c1 and http://test.org/c2'
        ' have a common individual http://test.org/x'
    )
    assert expected == result
开发者ID:RDFLib,项目名称:OWL-RL,代码行数:34,代码来源:test_class_axioms.py

示例2: test_spatial_both_geojson_and_wkt

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

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

        spatial_uri = URIRef('http://geonames/Newark')
        g.add((dataset, DCT.spatial, spatial_uri))

        g.add((spatial_uri, RDF.type, DCT.Location))
        g.add((spatial_uri,
               LOCN.geometry,
               Literal('{"type": "Point", "coordinates": [23, 45]}', datatype=GEOJSON_IMT)))
        g.add((spatial_uri,
               LOCN.geometry,
               Literal('POINT (67 89)', datatype=GSP.wktLiteral)))

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

        p.g = g

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

        extras = self._extras(datasets[0])

        eq_(extras['spatial'], '{"type": "Point", "coordinates": [23, 45]}')
开发者ID:pduchesne,项目名称:ckanext-dcat,代码行数:28,代码来源:test_euro_dcatap_profile_parse.py

示例3: generate_artistlist

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [as 别名]
def generate_artistlist(config, data):
	g = Graph('IOMemory', BNode())
	for artist_data in data['artists']:
		artist = URIRef(link(artist_data['link'])+"#subject")
		add_lang_names(g, artist, artist_data['names'], rel=[FOAF.name])
		g.add((artist, RDF.type, SCHEMA.MusicGroup))
	return g
开发者ID:qood,项目名称:vgmdb,代码行数:9,代码来源:rdf.py

示例4: testSub

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [as 别名]
    def testSub(self):
        g1 = self.graph
        g2 = Graph(store=g1.store)

        tarek = self.tarek
        # michel = self.michel
        bob = self.bob
        likes = self.likes
        # hates = self.hates
        pizza = self.pizza
        cheese = self.cheese

        g1.add((tarek, likes, pizza))
        g1.add((bob, likes, cheese))

        g2.add((bob, likes, cheese))

        g3 = g1 - g2

        self.assertEquals(len(g3), 1)
        self.assertEquals((tarek, likes, pizza) in g3, True)
        self.assertEquals((tarek, likes, cheese) in g3, False)

        self.assertEquals((bob, likes, cheese) in g3, False)

        g1 -= g2

        self.assertEquals(len(g1), 1)
        self.assertEquals((tarek, likes, pizza) in g1, True)
        self.assertEquals((tarek, likes, cheese) in g1, False)

        self.assertEquals((bob, likes, cheese) in g1, False)
开发者ID:Dataliberate,项目名称:rdflib,代码行数:34,代码来源:test_graph.py

示例5: test_distribution_format_format_normalized

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [as 别名]
    def test_distribution_format_format_normalized(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.mediaType, Literal('text/csv')))
        g.add((distribution1_1, DCT['format'], Literal('Comma Separated Values')))
        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]

        if toolkit.check_ckan_version(min_version='2.3'):
            eq_(resource['format'], u'CSV')
            eq_(resource['mimetype'], u'text/csv')
        else:
            eq_(resource['format'], u'Comma Separated Values')
开发者ID:pduchesne,项目名称:ckanext-dcat,代码行数:27,代码来源:test_euro_dcatap_profile_parse.py

示例6: rdf_get

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [as 别名]
 def rdf_get(self, departments):
     us_dept = URIRef('https://en.wikipedia.org/wiki/List_of_federal_agencies_in_the_United_States')
     g = Graph()
     for dept in departments:
         this_dept = URIRef('http://127.0.0.1:5000/departments/{0}'.format(urllib.quote(dept)))
         g.add((this_dept, RDF.type, us_dept,))
     return g.serialize(format='n3')
开发者ID:niall-oc,项目名称:things,代码行数:9,代码来源:app_rdf.py

示例7: annotateConfidence

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [as 别名]
def annotateConfidence(target, un, con, com):
    # thisAnnotation id is the full string, eg:
    # http://chartex.org/user/jjon/annotation/dc9d7cbdd0ebefb583e46fc2b79bc8cedde34d68
    # the last element being a hash (hashlib.sha1(oa:hastarget).hexdigest()) of this full string:
    # http://chartex.org/graphid/Person_11139might_bePerson_11339 (this triple is actually in there, why?, weird!
    target = re.sub('[<>]', '', target)
    thisAnnotationURI =  "http://chartex.org/user/%s/annotation/%s" % (un, sha1(target).hexdigest())
    confidence = Literal(con) if con == 'nochange' else Literal(con,datatype=XSD.decimal)
    #TODO: if no change, create no confidenceMetric triple for the annotation OR insert original decimal value
    
    if (int(annotationExists('<' + thisAnnotationURI + '>')) > 0):
        return ("You've already annotated this statement: %s \nPresumably you could make a separate annotation with a different username. If you start doing that, you should keep track of all your usernames. When we have authentication and session logic, this won't be necessary.\n\nAnnotation triples:\n" % (target,), getSingleConfidenceAnnotation('<' + thisAnnotationURI + '>', 'application/rdf+xml'))
    else:
        thisann = URIRef(thisAnnotationURI)
        g = Graph()
        bodyNode = BNode()
        triples = [
            (thisann, RDF.type, oa.Annotation),
            (thisann, oa.hasTarget, URIRef(target)),
            (thisann, oa.hasBody, bodyNode),
            (bodyNode, chartex.suggestedConfidenceMetric, confidence),
            (bodyNode, chartex.userComment, Literal(com))
        ]
        for t in triples: g.add(t)
        r = requests.post(
            AGVM_VC_REPO + "/statements",
            headers={'Content-Type': 'text/turtle'},
            data=g.serialize(format='turtle'),
            auth=AG_AUTH
        )

        return (g.serialize(format='pretty-xml'), r.__dict__)
开发者ID:jjon,项目名称:Graphing-ChartEx,代码行数:34,代码来源:cartametallon.py

示例8: directory_search_message

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [as 别名]
def directory_search_message(type):
    """
    Busca en el servicio de registro mandando un
    mensaje de request con una accion Seach del servicio de directorio

    Podria ser mas adecuado mandar un query-ref y una descripcion de registo
    con variables

    :param type:
    :return:
    """
    global mss_cnt
    logger.info('Buscamos en el servicio de registro')

    gmess = Graph()

    gmess.bind('foaf', FOAF)
    gmess.bind('dso', DSO)
    reg_obj = agn[AgentePersonal.name + '-search']
    gmess.add((reg_obj, RDF.type, DSO.Search))
    gmess.add((reg_obj, DSO.AgentType, type))

    msg = build_message(gmess, perf=ACL.request,
                        sender=AgentePersonal.uri,
                        receiver=DirectoryAgent.uri,
                        content=reg_obj,
                        msgcnt=mss_cnt)
    gr = send_message(msg, DirectoryAgent.address)
    mss_cnt += 1
    logger.info('Recibimos informacion del agente')

    return gr
开发者ID:AlbertSuarez,项目名称:Practica-ECSDI,代码行数:34,代码来源:SimplePersonalAgent.py

示例9: convert_graveyards

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [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

示例10: browser_retorna

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [as 别名]
def browser_retorna():
    global compres
    if request.method == 'GET':
        logger.info('Mostramos las compras realizadas')
        count, counts = get_all_sells()
        return render_template('retorna.html', compres=compres, count=count, sizes=counts)
    else:
        logger.info('Empezamos el proceso de devolucion')
        sells_checked = []
        for item in request.form.getlist("checkbox"):
            sells_checked.append(compres[int(item)][0])

        logger.info("Creando la peticion de compra")
        g = Graph()
        content = ECSDI['Peticion_retorno_' + str(get_count())]
        g.add((content, RDF.type, ECSDI.Peticion_retorno))
        for item in sells_checked:
            g.add((content, ECSDI.CompraRetornada, URIRef(item)))

        seller = get_agent_info(agn.SellerAgent, DirectoryAgent, UserPersonalAgent, get_count())

        send_message(
            build_message(g, perf=ACL.request, sender=UserPersonalAgent.uri, receiver=seller.uri,
                          msgcnt=get_count(),
                          content=content), seller.address)

        return render_template('endRetorna.html')
开发者ID:casassg,项目名称:ecsdi-amazon,代码行数:29,代码来源:UserPersonalAgent.py

示例11: infoagent_search_message

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [as 别名]
def infoagent_search_message(addr, ragn_uri):
    """
    Envia una accion a un agente de informacion
    """
    global mss_cnt
    logger.info('Hacemos una peticion al servicio de informacion')

    gmess = Graph()

    # Supuesta ontologia de acciones de agentes de informacion
    IAA = Namespace('IAActions')

    gmess.bind('foaf', FOAF)
    gmess.bind('iaa', IAA)
    reg_obj = agn[AgentePersonal.name + '-info-search']
    gmess.add((reg_obj, RDF.type, IAA.Search))

    msg = build_message(gmess, perf=ACL.request,
                        sender=AgentePersonal.uri,
                        receiver=ragn_uri,
                        msgcnt=mss_cnt)
    gr = send_message(msg, addr)
    mss_cnt += 1
    logger.info('Recibimos respuesta a la peticion al servicio de informacion')

    return gr
开发者ID:AlbertSuarez,项目名称:Practica-ECSDI,代码行数:28,代码来源:SimplePersonalAgent.py

示例12: _construct

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [as 别名]
def _construct(compiler, sources, query=None):
    dataset = ConjunctiveGraph()
    if not isinstance(sources, list):
        sources = [sources]
    for sourcedfn in sources:
        source = sourcedfn['source']
        graph = dataset.get_context(URIRef(sourcedfn.get('dataset') or source))
        if isinstance(source, (dict, list)):
            context_data = sourcedfn['context']
            if not isinstance(context_data, list):
                context_data = compiler.load_json(context_data )['@context']
            context_data = [compiler.load_json(ctx)['@context']
                            if isinstance(ctx, unicode) else ctx
                            for ctx in context_data]
            to_rdf(source, graph, context_data=context_data)
        elif isinstance(source, Graph):
            graph += source
        else:
            graph += compiler.cached_rdf(source)
    if not query:
        return graph
    with compiler.path(query).open() as fp:
        result = dataset.query(fp.read())
    g = Graph()
    for spo in result:
        g.add(spo)
    return g
开发者ID:libris,项目名称:lxltools,代码行数:29,代码来源:datacompiler.py

示例13: compareCommonTerms

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [as 别名]
def compareCommonTerms(terms,buff):
    global currentGraph, previousGraph, showDiffs
    currentGraph.bind("schema","http://schema.org/")
    currentGraph.bind("dc","http://purl.org/dc/terms/")
    currentGraph.bind("rdf",RDF)
    currentGraph.bind("rdfs",RDFS)
    changedCount = 0
    for t in sorted(terms):
        c = Graph()
        p = Graph()
        for trip in currentGraph.triples((URIRef(t),None,None)):
            c.add(trip)
        for trip in previousGraph.triples((URIRef(t),None,None)):
            p.add(trip)
        newg = c -  p
        dropg = p - c
        if len(newg) > 0 or len(dropg) > 0:
            changedCount += 1 
            buff.write( "   Changed term: %s\n" % t)
            if showDiffs:
                for s,p,o in newg.triples((None,None,None)):
                    buff.write( "       New:     %s %s %s\n" % (str(s),currentGraph.qname(p),o))
                for s,p,o in dropg.triples((None,None,None)):
                    buff.write( "       Dropped: %s %s %s\n" % (str(s),currentGraph.qname(p),o))
    return changedCount
开发者ID:BioSchemas,项目名称:schemaorg,代码行数:27,代码来源:compareterms.py

示例14: notify

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [as 别名]
def notify(uri):
    g = Graph()
    g.add((URIRef(uri), RDF.type, URIRef('http://www.bbc.co.uk/search/schema/ContentItem')))
    g.add((URIRef(uri), URIRef('http://www.bbc.co.uk/search/schema/url'), Literal(uri)))
    g.parse(uri)

    return g.serialize(format='nt').decode('utf-8')
开发者ID:avengerpenguin,项目名称:linked-data-search,代码行数:9,代码来源:tasks.py

示例15: test_post_no_type_to_base

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import add [as 别名]
 def test_post_no_type_to_base(self):
     graph = Graph()
     created = BNode()
     graph.add((self.my_ktbs.uri, RDFS.seeAlso, created))
     graph.add((created, RDF.type, KTBS.hasModel)) # in correct NS
     with assert_raises(RdfRestException):
         self.my_ktbs.post_graph(graph)
开发者ID:ktbs,项目名称:ktbs,代码行数:9,代码来源:test_ktbs_engine.py


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