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


Python ConjunctiveGraph.contexts方法代码示例

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


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

示例1: check

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]
    def check(kws):
        cg = ConjunctiveGraph()
        cg.parse(**kws)

        for g in cg.contexts():
            gid = g.identifier
            assert isinstance(gid, Identifier)
开发者ID:RDFLib,项目名称:rdflib,代码行数:9,代码来源:test_conjunctive_graph.py

示例2: test_nquads_default_graph

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]
def test_nquads_default_graph():
    ds = ConjunctiveGraph()

    data = """
    <http://example.org/s1> <http://example.org/p1> <http://example.org/o1> .
    <http://example.org/s2> <http://example.org/p2> <http://example.org/o2> .
    <http://example.org/s3> <http://example.org/p3> <http://example.org/o3> <http://example.org/g3> .
    """

    publicID = URIRef("http://example.org/g0")
    
    ds.parse(data=data, format="nquads", publicID=publicID)

    assert len(ds) == 3, len(g)
    assert len(list(ds.contexts())) == 2, len(list(ds.contexts()))
    assert len(ds.get_context(publicID)) == 2, len(ds.get_context(publicID))
开发者ID:dbs,项目名称:rdflib,代码行数:18,代码来源:test_issue535.py

示例3: test_serialize

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]
    def test_serialize(self):
        g = ConjunctiveGraph()
        uri1 = URIRef("http://example.org/mygraph1")
        uri2 = URIRef("http://example.org/mygraph2")

        bob = URIRef(u'urn:bob')
        likes = URIRef(u'urn:likes')
        pizza = URIRef(u'urn:pizza')

        g.get_context(uri1).add((bob, likes, pizza))
        g.get_context(uri2).add((bob, likes, pizza))

        s = g.serialize(format='nquads')
        self.assertEqual(len([x for x in s.split(b("\n")) if x.strip()]), 2)

        g2 = ConjunctiveGraph()
        g2.parse(data=s, format='nquads')

        self.assertEqual(len(g), len(g2))
        self.assertEqual(sorted(x.identifier for x in g.contexts()),
                         sorted(x.identifier for x in g2.contexts()))
开发者ID:Dataliberate,项目名称:rdflib,代码行数:23,代码来源:test_nquads.py

示例4: load_nquad_fixtures

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]
def load_nquad_fixtures(path=None):
    if not path:
        path = os.path.join(settings.DJANGO_ROOT, "void", "tests", "resources", "test_rdf_quads.nq")
    graph = ConjunctiveGraph()
    graph.parse(
        source=path,
        format='nquads'
    )
    store = rdfstore._rdfstore_test
    graph_store = store.get_graph_store
    for context in graph.contexts():
        graph_store.put(context.identifier.strip("<>"), context)
    return graph
开发者ID:delving,项目名称:nave,代码行数:15,代码来源:test_tasks.py

示例5: readIsomorphicGraph

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]
    def readIsomorphicGraph(self, file):
        graph = ConjunctiveGraph(identifier='')

        # check if we handle a directory or a seperate file
        if isdir(file):
            # for a better readability rename variable
            dir = file
            for path, dirs, files in walk(file):
                for file in files:
                    absfile = join(path, file)
                    format = rdflib.util.guess_format(absfile)

                    if format is not None:
                        graph.parse(absfile, format=format, publicID=self.nsQuitDiff)

        elif isfile(file):
            format = rdflib.util.guess_format(file)

            if format is not None:
                graph.parse(file, format=format, publicID=self.nsQuitDiff)

        contextDict = {}
        contextDict[self.nsQuitDiff] = Graph()

        for subgraph in graph.contexts():
            # TODO we have to copy all the triples to a new ConjunctiveGraph
            # because https://rdflib.readthedocs.io/en/stable/_modules/rdflib/compare.html takes the complete store
            # and thus doesn't support quads
            triples = subgraph.triples((None, None, None))
            if isinstance(subgraph.identifier, BNode) or str(subgraph.identifier) == self.nsQuitDiff:
                subgraphConjunctive = contextDict[self.nsQuitDiff]
            else:
                try:
                    subGraphConjunctive = contextDict[subgraph.identifier]
                except:
                    contextDict[subgraph.identifier] = ConjunctiveGraph()
                    subgraphConjunctive = contextDict[subgraph.identifier]

            for triple in triples:
                subgraphConjunctive.add(triple)
            # end TODO hack

        graphDict = {}

        for identifier, graph in contextDict.items():
            graphDict[identifier] = compare.to_isomorphic(graph)

        return graphDict
开发者ID:AKSW,项目名称:QuitDiff,代码行数:50,代码来源:QuitDiff.py

示例6: datasetInfo

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]
def datasetInfo():
    from optparse import OptionParser
    usage = '''usage: %prog [options] <DB Type>'''
    op = OptionParser(usage=usage)
    op.add_option('-c', '--connection', help='Database connection string')
    op.add_option('-i', '--id', help='Database table set identifier')
    (options, args) = op.parse_args()

    store = plugin.get(args[0], Store)(options.id)
    store.open(options.connection)
    dataset = ConjunctiveGraph(store)
    sdGraph = Graph()

    SD_NS = Namespace('http://www.w3.org/ns/sparql-service-description#')
    SCOVO = Namespace('http://purl.org/NET/scovo#')
    VOID  = Namespace('http://rdfs.org/ns/void#')
    
    sdGraph.bind(u'sd',SD_NS)
    sdGraph.bind(u'scovo',SCOVO)
    sdGraph.bind(u'void',VOID)

    service = BNode()
    datasetNode = BNode()
    sdGraph.add((service,RDF.type,SD_NS.Service))
    sdGraph.add((service,SD_NS.defaultDatasetDescription,datasetNode))
    sdGraph.add((datasetNode,RDF.type,SD_NS.Dataset))
    for graph in dataset.contexts():
        graphNode  = BNode()
        graphNode2 = BNode()
        sdGraph.add((datasetNode,SD_NS.namedGraph,graphNode))
        sdGraph.add((graphNode,SD_NS.name,URIRef(graph.identifier)))
        sdGraph.add((graphNode,SD_NS.graph,graphNode2))
        sdGraph.add((graphNode2,RDF.type,SD_NS.Graph))
        statNode = BNode()
        sdGraph.add((graphNode2,SD_NS.statItem,statNode))
        sdGraph.add((statNode,SCOVO.dimension,VOID.numberOfTriples))
        noTriples = Literal(len(graph))
        sdGraph.add((statNode,RDF.value,noTriples))
    print sdGraph.serialize(format='pretty-xml')
开发者ID:KiranAjayakumar,项目名称:python-dlp,代码行数:41,代码来源:RDFload.py

示例7: __load_graph

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]
def __load_graph(file_path):
    errors = ""
    current_graph = ConjunctiveGraph()

    try:
        with open(file_path) as f:
            json_ld_file = json.load(f)
            if isinstance(json_ld_file, dict):
                json_ld_file = [json_ld_file]

            for json_ld_resource in json_ld_file:
                # Trick to force the use of a pre-loaded context if the format
                # specified is JSON-LD
                cur_context = json_ld_resource["@context"]
                json_ld_resource["@context"] = context_json

                current_graph.parse(data=json.dumps(json_ld_resource), format="json-ld")

            return list(current_graph.contexts())[0]
    except Exception as e:
        errors = " | " + str(e)  # Try another format

    raise IOError("[1]", "It was impossible to handle the format used for storing the file '%s'%s" %
                  (file_path, errors))
开发者ID:essepuntato,项目名称:opencitations,代码行数:26,代码来源:fix_prov_to_single_file.py

示例8: SQLATestCase

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]
class SQLATestCase(unittest.TestCase):
    identifier = URIRef("rdflib_test")
    dburi = Literal('sqlite://')

    def setUp(self):
        self.store = plugin.get(
            "SQLAlchemy", Store)(identifier=self.identifier)
        self.graph = ConjunctiveGraph(self.store, identifier=self.identifier)
        self.graph.open(self.dburi, create=True)

    def tearDown(self):
        self.graph.destroy(self.dburi)
        try:
            self.graph.close()
        except:
            pass

    def test_registerplugins(self):
        # I doubt this is quite right for a fresh pip installation,
        # this test is mainly here to fill a coverage gap.
        from rdflib_sqlalchemy import registerplugins
        from rdflib import plugin
        from rdflib.store import Store
        registerplugins()
        self.assert_(plugin.get('SQLAlchemy', Store) is not None)
        p = plugin._plugins
        self.assert_(('SQLAlchemy', Store) in p, p)
        del p[('SQLAlchemy', Store)]
        plugin._plugins = p
        registerplugins()
        self.assert_(('SQLAlchemy', Store) in p, p)

    def test_skolemisation(self):
        from rdflib_sqlalchemy.SQLAlchemy import skolemise
        testbnode = BNode()
        statemnt = (michel, likes, testbnode)
        res = skolemise(statemnt)
        self.assert_('bnode:N' in str(res[2]), res)

    def test_deskolemisation(self):
        from rdflib_sqlalchemy.SQLAlchemy import deskolemise
        testbnode = BNode()
        statemnt = (michel, likes, testbnode)
        res = deskolemise(statemnt)
        self.assert_(str(res[2]).startswith('N'), res)

    def test_redeskolemisation(self):
        from rdflib_sqlalchemy.SQLAlchemy import skolemise, deskolemise
        testbnode = BNode()
        statemnt = skolemise((michel, likes, testbnode))
        res = deskolemise(statemnt)
        self.assert_(str(res[2]).startswith('N'), res)

    def test__parse_rfc1738_args(self):
        from rdflib_sqlalchemy.SQLAlchemy import _parse_rfc1738_args
        self.assertRaises(ValueError, _parse_rfc1738_args, 'Not parseable')

    def test_namespaces(self):
        self.assert_(list(self.graph.namespaces()) != [])

    def test_contexts_without_triple(self):
        self.assert_(list(self.graph.contexts()) == [])

    def test_contexts_with_triple(self):
        statemnt = (michel, likes, pizza)
        self.assert_(self.graph.contexts(triple=statemnt) != [])

    def test__len(self):
        self.assert_(self.store.__len__() == 0)

    def test__remove_context(self):
        self.store._remove_context(self.identifier)
开发者ID:IRI-Research,项目名称:rdflib-sqlalchemy,代码行数:74,代码来源:test_sqlalchemy.py

示例9: TestSparql11

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]
class TestSparql11(unittest.TestCase):

    def setUp(self):
        self.longMessage = True
        self.graph = ConjunctiveGraph('SPARQLUpdateStore')

        root = HOST + DB
        self.graph.open((root + "sparql", root + "update"))

        # clean out the store
        for c in self.graph.contexts():
            c.remove((None, None, None))
            assert len(c) == 0

    def tearDown(self):
        self.graph.close()

    def testSimpleGraph(self):
        g = self.graph.get_context(graphuri)
        g.add((tarek, likes, pizza))
        g.add((bob, likes, pizza))
        g.add((bob, likes, cheese))

        g2 = self.graph.get_context(othergraphuri)
        g2.add((michel, likes, pizza))

        self.assertEquals(3, len(g), 'graph contains 3 triples')
        self.assertEquals(1, len(g2), 'other graph contains 1 triple')

        r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEquals(2, len(list(r)), "two people like pizza")

        r = g.triples((None, likes, pizza))
        self.assertEquals(2, len(list(r)), "two people like pizza")

        # Test initBindings
        r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }",
                    initBindings={'s': tarek})
        self.assertEquals(1, len(list(r)), "i was asking only about tarek")

        r = g.triples((tarek, likes, pizza))
        self.assertEquals(1, len(list(r)), "i was asking only about tarek")

        r = g.triples((tarek, likes, cheese))
        self.assertEquals(0, len(list(r)), "tarek doesn't like cheese")

        g2.add((tarek, likes, pizza))
        g.remove((tarek, likes, pizza))
        r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEquals(1, len(list(r)), "only bob likes pizza")

    def testConjunctiveDefault(self):
        g = self.graph.get_context(graphuri)
        g.add((tarek, likes, pizza))
        g2 = self.graph.get_context(othergraphuri)
        g2.add((bob, likes, pizza))
        g.add((tarek, hates, cheese))

        self.assertEquals(2, len(g), 'graph contains 2 triples')

        # the following are actually bad tests as they depend on your endpoint,
        # as pointed out in the sparqlstore.py code:
        #
        ## For ConjunctiveGraphs, reading is done from the "default graph" Exactly
        ## what this means depends on your endpoint, because SPARQL does not offer a
        ## simple way to query the union of all graphs as it would be expected for a
        ## ConjuntiveGraph.
        ##
        ## Fuseki/TDB has a flag for specifying that the default graph
        ## is the union of all graphs (tdb:unionDefaultGraph in the Fuseki config).
        self.assertEquals(3, len(self.graph),
            'default union graph should contain three triples but contains:\n'
            '%s' % list(self.graph))

        r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEquals(2, len(list(r)), "two people like pizza")

        r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }",
                             initBindings={'s': tarek})
        self.assertEquals(1, len(list(r)), "i was asking only about tarek")

        r = self.graph.triples((tarek, likes, pizza))
        self.assertEquals(1, len(list(r)), "i was asking only about tarek")

        r = self.graph.triples((tarek, likes, cheese))
        self.assertEquals(0, len(list(r)), "tarek doesn't like cheese")

        g2.remove((bob, likes, pizza))

        r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEquals(1, len(list(r)), "only tarek likes pizza")

    def testUpdate(self):
        self.graph.update("INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> . } }")

        g = self.graph.get_context(graphuri)
        self.assertEquals(1, len(g), 'graph contains 1 triples')

    def testUpdateWithInitNs(self):
        self.graph.update(
#.........这里部分代码省略.........
开发者ID:Dataliberate,项目名称:rdflib,代码行数:103,代码来源:test_sparqlupdatestore.py

示例10: TestSparql11

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]
class TestSparql11(unittest.TestCase):

    def setUp(self):
        self.longMessage = True
        self.graph = ConjunctiveGraph('SPARQLUpdateStore')

        root = "http://localhost:3030/ukpp/"
        self.graph.open((root + "sparql", root + "update"))

        # clean out the store
        for c in self.graph.contexts():
            c.remove((None, None, None))
            assert len(c) == 0

    def tearDown(self):
        self.graph.close()

    def testSimpleGraph(self):
        g = self.graph.get_context(graphuri)
        g.add((tarek, likes, pizza))
        g.add((bob, likes, pizza))
        g.add((bob, likes, cheese))

        g2 = self.graph.get_context(othergraphuri)
        g2.add((michel, likes, pizza))

        self.assertEquals(3, len(g), 'graph contains 3 triples')
        self.assertEquals(1, len(g2), 'other graph contains 1 triple')

        r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEquals(2, len(list(r)), "two people like pizza")

        r = g.triples((None, likes, pizza))
        self.assertEquals(2, len(list(r)), "two people like pizza")

        # Test initBindings
        r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }",
                    initBindings={'s': tarek})
        self.assertEquals(1, len(list(r)), "i was asking only about tarek")

        r = g.triples((tarek, likes, pizza))
        self.assertEquals(1, len(list(r)), "i was asking only about tarek")

        r = g.triples((tarek, likes, cheese))
        self.assertEquals(0, len(list(r)), "tarek doesn't like cheese")

        g2.add((tarek, likes, pizza))
        g.remove((tarek, likes, pizza))
        r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEquals(1, len(list(r)), "only bob likes pizza")

    def testConjunctiveDefault(self):
        g = self.graph.get_context(graphuri)
        g.add((tarek, likes, pizza))
        g2 = self.graph.get_context(othergraphuri)
        g2.add((bob, likes, pizza))
        g.add((tarek, hates, cheese))

        self.assertEquals(2, len(g), 'graph contains 2 triples')
        self.assertEquals(3, len(self.graph),
                          'default union graph contains three triples')

        r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEquals(2, len(list(r)), "two people like pizza")

        r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }",
                             initBindings={'s': tarek})
        self.assertEquals(1, len(list(r)), "i was asking only about tarek")

        r = self.graph.triples((tarek, likes, pizza))
        self.assertEquals(1, len(list(r)), "i was asking only about tarek")

        r = self.graph.triples((tarek, likes, cheese))
        self.assertEquals(0, len(list(r)), "tarek doesn't like cheese")

        g2.remove((bob, likes, pizza))

        r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEquals(1, len(list(r)), "only tarek likes pizza")

    def testUpdate(self):
        self.graph.update("INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> . } }")
        
        g = self.graph.get_context(graphuri)
        self.assertEquals(1, len(g), 'graph contains 1 triples')
        
    def testUpdateWithInitNs(self):
        self.graph.update(
            "INSERT DATA { GRAPH ns:graph { ns:michel ns:likes ns:pizza . } }",
            initNs={'ns': URIRef('urn:')}
        )
        
        g = self.graph.get_context(graphuri)
        self.assertEquals(
            set(g.triples((None,None,None))),
            set([(michel,likes,pizza)]),
            'only michel likes pizza'
        )
        
    def testUpdateWithInitBindings(self):
#.........这里部分代码省略.........
开发者ID:JesusPatate,项目名称:rdflib,代码行数:103,代码来源:test_sparqlupdatestore.py

示例11: ContextTestCase

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]

#.........这里部分代码省略.........
    def testRemoveInMultipleContexts(self):
        c1 = self.c1
        c2 = self.c2
        triple = (self.pizza, self.hates, self.tarek)  # revenge!

        self.addStuffInMultipleContexts()

        # triple should be still in store after removing it from c1 + c2
        self.assert_(triple in self.graph)
        graph = Graph(self.graph.store, c1)
        graph.remove(triple)
        self.assert_(triple in self.graph)
        graph = Graph(self.graph.store, c2)
        graph.remove(triple)
        self.assert_(triple in self.graph)
        self.graph.remove(triple)
        # now gone!
        self.assert_(triple not in self.graph)

        # add again and see if remove without context removes all triples!
        self.addStuffInMultipleContexts()
        self.graph.remove(triple)
        self.assert_(triple not in self.graph)

    def testContexts(self):
        triple = (self.pizza, self.hates, self.tarek)  # revenge!

        self.addStuffInMultipleContexts()

        def cid(c):
            if (PY3 and not isinstance(c,(str, bytes))) or not isinstance(c, basestring):
                return c.identifier
            return c
        self.assert_(self.c1 in list(map(cid, self.graph.contexts())))
        self.assert_(self.c2 in list(map(cid, self.graph.contexts())))

        contextList = list(map(cid, list(self.graph.contexts(triple))))
        self.assert_(self.c1 in contextList)
        self.assert_(self.c2 in contextList)

    def testRemoveContext(self):
        c1 = self.c1

        self.addStuffInMultipleContexts()
        self.assertEquals(len(Graph(self.graph.store, c1)), 1)
        self.assertEquals(len(self.get_context(c1)), 1)

        self.graph.remove_context(self.get_context(c1))
        self.assert_(self.c1 not in self.graph.contexts())

    def testRemoveAny(self):
        Any = None
        self.addStuffInMultipleContexts()
        self.graph.remove((Any, Any, Any))
        self.assertEquals(len(self.graph), 0)

    def testTriples(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        asserte = self.assertEquals
开发者ID:IRI-Research,项目名称:rdflib-sqlalchemy,代码行数:70,代码来源:context_case.py

示例12: Graph

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]
     <{0}> ?seq_index ?media_item .
     ?media_item rdf:type <{1}> .
     ?media_item sg:images ?media_item_seq .
     ?media_item_seq ?media_item_seq_index ?media_item_instance .
     ?media_item_instance sg:stillImageType "thumbnail" .
     ?media_item_instance sg:stillImageURL ?stillImageURL .
}}
"""
query = template.format('Nf8afb396966049fd8db7ffa930f816ee', 'http://example.com/rdf/schemas/StillImage')

for idx, elNode, elType, imgType, imgUrl in ug.query(query):
  print idx, elNode, elType, imgType, imgUrl

# query for all contexts and all properties related by domain
#
for ctx in citg.contexts():
  g = Graph(citg.store, ctx.identifier)
  rs = g.query(' \
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \
    PREFIX owl: <http://www.w3.org/2002/07/owl#> \
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
    SELECT ?class ?label \
    WHERE { { ?class rdf:type owl:Class OPTIONAL { ?class rdfs:label ?label } } \
    UNION { ?class rdf:type rdfs:Class OPTIONAL { ?class rdfs:label ?label } } } \
    ORDER BY ?label')
  for c in rs:
    print c[0], ' -----'
    print
    rs2 = g.query(' \
      PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \
      PREFIX owl: <http://www.w3.org/2002/07/owl#> \
开发者ID:hburrows,项目名称:cataloger,代码行数:33,代码来源:scratch.py

示例13: unicode

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]

    jldDict["@context"] = context
    jldJson = json.dumps(jldDict).replace("_!DOMEO_NS!_", ":")
    jldJson = jldJson.replace('ao:prefix": ""','ao:prefix": "xsd:String"').replace('ao:suffix": ""','ao:suffix": "xsd:String"').replace('statement": ""','statement": "xsd:String"').replace('modality": ""','modality": "xsd:String"').replace('SIO_000228": ""','SIO_000228": "xsd:String"').replace('pav:previousVersion": ""','pav:previousVersion": "xsd:String"').replace('assertionType": ""','assertionType": "xsd:String"')

    jldJson = unicode(jldJson).encode(encoding="utf-8",errors="replace")
        #print jldJson

    g = Graph(store=store,identifier=jld["_id"]).parse(data=jldJson, format='json-ld')


    if VERBOSE:
        print jldJson

# enumerate contexts
if VERBOSE:
    print "Graph contexts stored in IO memory"
    for c in cGraph.contexts():
        print("-- %s " % c)

# TODO: add exception handling
s = unicode(cGraph.serialize(format='xml', indent=4), encoding="utf-8",errors="replace")
if VERBOSE:
    print s

# TODO: add exception handling
f = codecs.open(OUT_FILE,'w','utf-8')
f.write(s)
f.close()
开发者ID:dbmi-pitt,项目名称:domeo-tools,代码行数:31,代码来源:convertDDIJsonLDToRDF.py

示例14: TestSparql11

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]
class TestSparql11(unittest.TestCase):

    def setUp(self):
        self.longMessage = True
        self.graph = ConjunctiveGraph('SPARQLUpdateStore')

        root = "http://localhost:3030/ukpp/"
        self.graph.open((root + "sparql", root + "update"))

        # clean out the store
        for c in self.graph.contexts():
            c.remove((None, None, None))
            assert len(c) == 0

    def tearDown(self):
        self.graph.close()

    def testSimpleGraph(self):
        g = self.graph.get_context(graphuri)
        g.add((tarek, likes, pizza))
        g.add((bob, likes, pizza))
        g.add((bob, likes, cheese))

        g2 = self.graph.get_context(othergraphuri)
        g2.add((michel, likes, pizza))

        self.assertEquals(3, len(g), 'graph contains 3 triples')
        self.assertEquals(1, len(g2), 'other graph contains 1 triple')

        r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEquals(2, len(list(r)), "two people like pizza")

        r = g.triples((None, likes, pizza))
        self.assertEquals(2, len(list(r)), "two people like pizza")

        # Test initBindings
        r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }",
                    initBindings={'s': tarek})
        self.assertEquals(1, len(list(r)), "i was asking only about tarek")

        r = g.triples((tarek, likes, pizza))
        self.assertEquals(1, len(list(r)), "i was asking only about tarek")

        r = g.triples((tarek, likes, cheese))
        self.assertEquals(0, len(list(r)), "tarek doesn't like cheese")

        g2.add((tarek, likes, pizza))
        g.remove((tarek, likes, pizza))
        r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEquals(1, len(list(r)), "only bob likes pizza")

    def testConjunctiveDefault(self):
        g = self.graph.get_context(graphuri)
        g.add((tarek, likes, pizza))
        g2 = self.graph.get_context(othergraphuri)
        g2.add((bob, likes, pizza))
        g.add((tarek, hates, cheese))

        self.assertEquals(2, len(g), 'graph contains 2 triples')
        self.assertEquals(3, len(self.graph),
                          'default union graph contains three triples')

        r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEquals(2, len(list(r)), "two people like pizza")

        r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }",
                             initBindings={'s': tarek})
        self.assertEquals(1, len(list(r)), "i was asking only about tarek")

        r = self.graph.triples((tarek, likes, pizza))
        self.assertEquals(1, len(list(r)), "i was asking only about tarek")

        r = self.graph.triples((tarek, likes, cheese))
        self.assertEquals(0, len(list(r)), "tarek doesn't like cheese")

        g2.remove((bob, likes, pizza))

        r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEquals(1, len(list(r)), "only tarek likes pizza")

    def testUpdate(self):
        self.graph.update("INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> . } }")
        
        g = self.graph.get_context(graphuri)
        self.assertEquals(1, len(g), 'graph contains 1 triples')
        
    def testUpdateWithInitNs(self):
        self.graph.update(
            "INSERT DATA { GRAPH ns:graph { ns:michel ns:likes ns:pizza . } }",
            initNs={'ns': URIRef('urn:')}
        )
        
        g = self.graph.get_context(graphuri)
        self.assertEquals(
            set(g.triples((None,None,None))),
            set([(michel,likes,pizza)]),
            'only michel likes pizza'
        )
        
    def testUpdateWithInitBindings(self):
#.........这里部分代码省略.........
开发者ID:Perif,项目名称:rdflib,代码行数:103,代码来源:test_sparqlupdatestore.py

示例15: TestSparql11

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import contexts [as 别名]
class TestSparql11(unittest.TestCase):

    def setUp(self):
        self.longMessage = True
        self.graph = ConjunctiveGraph('SPARQLUpdateStore')

        root = HOST + DB
        self.graph.open((root + "sparql", root + "update"))

        # clean out the store
        for c in self.graph.contexts():
            c.remove((None, None, None))
            assert len(c) == 0

    def tearDown(self):
        self.graph.close()

    def testSimpleGraph(self):
        g = self.graph.get_context(graphuri)
        g.add((tarek, likes, pizza))
        g.add((bob, likes, pizza))
        g.add((bob, likes, cheese))

        g2 = self.graph.get_context(othergraphuri)
        g2.add((michel, likes, pizza))

        self.assertEqual(3, len(g), 'graph contains 3 triples')
        self.assertEqual(1, len(g2), 'other graph contains 1 triple')

        r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEqual(2, len(list(r)), "two people like pizza")

        r = g.triples((None, likes, pizza))
        self.assertEqual(2, len(list(r)), "two people like pizza")

        # Test initBindings
        r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }",
                    initBindings={'s': tarek})
        self.assertEqual(1, len(list(r)), "i was asking only about tarek")

        r = g.triples((tarek, likes, pizza))
        self.assertEqual(1, len(list(r)), "i was asking only about tarek")

        r = g.triples((tarek, likes, cheese))
        self.assertEqual(0, len(list(r)), "tarek doesn't like cheese")

        g2.add((tarek, likes, pizza))
        g.remove((tarek, likes, pizza))
        r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEqual(1, len(list(r)), "only bob likes pizza")

    def testConjunctiveDefault(self):
        g = self.graph.get_context(graphuri)
        g.add((tarek, likes, pizza))
        g2 = self.graph.get_context(othergraphuri)
        g2.add((bob, likes, pizza))
        g.add((tarek, hates, cheese))

        self.assertEqual(2, len(g), 'graph contains 2 triples')

        # the following are actually bad tests as they depend on your endpoint,
        # as pointed out in the sparqlstore.py code:
        #
        ## For ConjunctiveGraphs, reading is done from the "default graph" Exactly
        ## what this means depends on your endpoint, because SPARQL does not offer a
        ## simple way to query the union of all graphs as it would be expected for a
        ## ConjuntiveGraph.
        ##
        ## Fuseki/TDB has a flag for specifying that the default graph
        ## is the union of all graphs (tdb:unionDefaultGraph in the Fuseki config).
        self.assertEqual(3, len(self.graph),
            'default union graph should contain three triples but contains:\n'
            '%s' % list(self.graph))

        r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEqual(2, len(list(r)), "two people like pizza")

        r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }",
                             initBindings={'s': tarek})
        self.assertEqual(1, len(list(r)), "i was asking only about tarek")

        r = self.graph.triples((tarek, likes, pizza))
        self.assertEqual(1, len(list(r)), "i was asking only about tarek")

        r = self.graph.triples((tarek, likes, cheese))
        self.assertEqual(0, len(list(r)), "tarek doesn't like cheese")

        g2.remove((bob, likes, pizza))

        r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }")
        self.assertEqual(1, len(list(r)), "only tarek likes pizza")

    def testUpdate(self):
        self.graph.update("INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> . } }")

        g = self.graph.get_context(graphuri)
        self.assertEqual(1, len(g), 'graph contains 1 triples')

    def testUpdateWithInitNs(self):
        self.graph.update(
#.........这里部分代码省略.........
开发者ID:drewp,项目名称:rdflib,代码行数:103,代码来源:test_sparqlupdatestore.py


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