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


Python ConjunctiveGraph.get_context方法代码示例

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


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

示例1: test_dSet_parsed_as_context_returns_results

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
 def test_dSet_parsed_as_context_returns_results(self):
     querystr = """SELECT DISTINCT ?s FROM <http://test/> { ?s ?p ?o }"""
     graph = ConjunctiveGraph()
     graph.get_context(URIRef('http://test/')
                         ).parse("http://www.w3.org/People/Berners-Lee/card.rdf")
     r = graph.query(querystr, loadContexts=True)
     self.assert_(len(r.bindings) is not 0)
开发者ID:RDFLib,项目名称:rdfextras,代码行数:9,代码来源:test_sparql_load_contexts.py

示例2: _graphFromQuads2

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def _graphFromQuads2(q):
    g = ConjunctiveGraph()
    #g.addN(q) # no effect on nquad output
    for s,p,o,c in q:
        g.get_context(c).add((s,p,o)) # kind of works with broken rdflib nquad serializer code
        #g.store.add((s,p,o), c) # no effect on nquad output
    return g
开发者ID:,项目名称:,代码行数:9,代码来源:

示例3: test_dSet_parsed_as_URL_raises_Exception

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
 def test_dSet_parsed_as_URL_raises_Exception(self):
     querystr = """SELECT DISTINCT ?s FROM <http://test/> { ?s ?p ?o }"""
     graph = ConjunctiveGraph()
     graph.get_context(URIRef("http://test/")
                         ).parse("http://www.w3.org/People/Berners-Lee/card.rdf")
     self.assertRaises((URLError, UriException), 
             graph.query, (querystr), loadContexts=False)
开发者ID:RDFLib,项目名称:rdfextras,代码行数:9,代码来源:test_sparql_load_contexts.py

示例4: NQSink

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
class NQSink(object):
    def __init__(self, graph):
        # NQuads is a context-aware format.
        self.graph = ConjunctiveGraph(store = graph.store)

    def quad(self, s, p, o, c):
        self.graph.get_context(c).add((s, p, o))
开发者ID:npilon,项目名称:pymantic,代码行数:9,代码来源:parsers.py

示例5: test_quad_contexts

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def test_quad_contexts():
    g = ConjunctiveGraph()
    a = URIRef('urn:a')
    b = URIRef('urn:b')
    g.get_context(a).add((a, a, a))
    g.addN([(b, b, b, b)])

    assert set(g) == set([(a, a, a), (b, b, b)])
    for q in g.quads():
        assert isinstance(q[3], Graph)
开发者ID:RDFLib,项目名称:rdflib,代码行数:12,代码来源:test_conjunctive_graph.py

示例6: NQuadsParser

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
class NQuadsParser(NTriplesParser):

    def parse(self, inputsource, sink, **kwargs):
        """Parse f as an N-Triples file."""
        assert sink.store.context_aware, ("NQuadsParser must be given"
                                          " a context aware store.")
        self.sink = ConjunctiveGraph(store=sink.store, identifier=sink.identifier)

        source = inputsource.getByteStream()

        if not hasattr(source, 'read'):
            raise ParseError("Item to parse must be a file-like object.")

        source = getreader('utf-8')(source)

        self.file = source
        self.buffer = ''
        while True:
            self.line = __line = self.readline()
            if self.line is None:
                break
            try:
                self.parseline()
            except ParseError as msg:
                raise ParseError("Invalid line (%s):\n%r" % (msg, __line))

        return self.sink

    def parseline(self):
        self.eat(r_wspace)
        if (not self.line) or self.line.startswith(('#')):
            return  # The line is empty or a comment

        subject = self.subject()
        self.eat(r_wspace)

        predicate = self.predicate()
        self.eat(r_wspace)

        obj = self.object()
        self.eat(r_wspace)

        context = self.uriref() or self.nodeid() or self.sink.identifier
        self.eat(r_tail)

        if self.line:
            raise ParseError("Trailing garbage")
        # Must have a context aware store - add on a normal Graph
        # discards anything where the ctx != graph.identifier
        self.sink.get_context(context).add((subject, predicate, obj))
开发者ID:RDFLib,项目名称:rdflib,代码行数:52,代码来源:nquads.py

示例7: test_nquads_default_graph

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

示例8: _construct

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

示例9: __store_graph

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def __store_graph(cur_g, rdf_iri_string, d_dir):
    try:
        res_dir, dest_file = \
            find_paths(rdf_iri_string, args.base + os.sep, "https://w3id.org/oc/corpus/", 10000, 1000)
        
        dest_dir = res_dir.replace(args.base + os.sep, d_dir + os.sep)
        if not os.path.exists(dest_dir):
            os.makedirs(dest_dir)
        
        cur_file = dest_file.replace(res_dir, dest_dir)
        if os.path.exists(cur_file):
            c_graph = __load_graph(cur_file)
        else:
            c_graph = ConjunctiveGraph()

        c_graph.remove_context(c_graph.get_context(cur_g.identifier))
        c_graph.addN([item + (cur_g.identifier,) for item in list(cur_g)])
        
        with open(dest_file.replace(res_dir, dest_dir), "w") as f:
            cur_json_ld = json.loads(c_graph.serialize(format="json-ld", context=context_json))
            cur_json_ld["@context"] = context_path
            json.dump(cur_json_ld, f, indent=4)
        # repok.add_sentence("File '%s' added." % cur_file)
        return dest_file
    except Exception as e:
        reperr.add_sentence("[5] It was impossible to store the RDF statements in %s. %s" %
                            (dest_file, str(e)))
开发者ID:essepuntato,项目名称:opencitations,代码行数:29,代码来源:fix_prov_to_clashing_updates.py

示例10: test_bnode_publicid

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def test_bnode_publicid():

    g = ConjunctiveGraph()
    b = BNode()
    data = '<d:d> <e:e> <f:f> .'
    print("Parsing %r into %r" % (data, b))
    g.parse(data=data, format='turtle', publicID=b)

    triples = list(g.get_context(b).triples((None, None, None)))
    if not triples:
        raise Exception("No triples found in graph %r" % b)

    u = URIRef(b)

    triples = list(g.get_context(u).triples((None, None, None)))
    if triples:
        raise Exception("Bad: Found in graph %r: %r" % (u, triples))
开发者ID:RDFLib,项目名称:rdflib,代码行数:19,代码来源:test_conjunctive_graph.py

示例11: graph

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
    def graph(self):
        g = ConjunctiveGraph()
        for prefix in self.__prefixes:
            g.bind(prefix, self.__prefixes[prefix])
        variables = {}

        def nodify(elm):
            if is_variable(elm):
                if not (elm in variables):
                    elm_node = BNode(elm)
                    variables[elm] = elm_node
                return variables[elm]
            else:
                if elm == 'a':
                    return RDF.type
                elif elm.startswith('"'):
                    return Literal(elm.lstrip('"').rstrip('"'))
                else:
                    try:
                        return float(elm)
                    except ValueError:
                        return URIRef(elm)

        nxg = nx.Graph()
        for (s, p, o) in self._tps:
            nxg.add_nodes_from([s, o])
            nxg.add_edge(s, o)

        contexts = dict([(str(index), c) for (index, c) in enumerate(nx.connected_components(nxg))])

        for (s, p, o) in self._tps:
            s_node = nodify(s)
            o_node = nodify(o)
            p_node = nodify(p)

            context = None
            for uid in contexts:
                if s in contexts[uid]:
                    context = str(uid)

            g.get_context(context).add((s_node, p_node, o_node))

        return g
开发者ID:SmartDeveloperHub,项目名称:agora-planner,代码行数:45,代码来源:agp.py

示例12: test_serialize

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [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:d3vgru,项目名称:rdflib,代码行数:22,代码来源:test_nquads.py

示例13: generate_config_file

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def generate_config_file(data_source, rdf_data=None, rdf_format=None, sparql_url=None, sparql_graph=None):
    current_task.update_state(state='PROGRESS', meta={'progress_percent': 15, 'progress_msg': 'Reading provided RDF data...'})

    try:
        if data_source == 'rdf':
            data_graph = Graph()
            data_graph.parse(format=rdf_format, data=rdf_data)
        else:
            g = ConjunctiveGraph('SPARQLStore')
            g.open(sparql_url)
            data_graph = g.get_context(sparql_graph) if sparql_graph else g
    except Exception, e:
        raise Exception("An error occurred while trying to read provided data source: %s" % str(e))
开发者ID:jonlazaro,项目名称:linked-tag-world,代码行数:15,代码来源:tasks.py

示例14: get_ltw_data_graph

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def get_ltw_data_graph(graph_id=None):
    if not graph_id:
        ltwapp = App.query.filter_by(id=session['app']).first()
        graph_id = ltwapp.graph_id
    if graph_id:
        Virtuoso = plugin("Virtuoso", Store)
        store = Virtuoso(app.config['VIRTUOSO_ODBC'])
        ltw_data_graph = ConjunctiveGraph(store=store)
        g = ltw_data_graph.get_context(graph_id)

        # Initialization step needed to make Virtuoso library work
        g.add((URIRef('initializationstuff'), URIRef('initializationstuff'), URIRef('initializationstuff')))
        g.remove((URIRef('initializationstuff'), URIRef('initializationstuff'), URIRef('initializationstuff')))

        return g
    else:
        return None
开发者ID:jonlazaro,项目名称:linked-tag-world,代码行数:19,代码来源:utils.py

示例15: GraphCache

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
class GraphCache(object):

    def __init__(self, cachedir):
        self.graph = ConjunctiveGraph()
        self.mtime_map = {}
        self.cachedir = cachedir
        if not os.path.isdir(cachedir):
            os.makedirs(cachedir)

    def load(self, url):
        src = VOCAB_SOURCE_MAP.get(str(url), url)
        if os.path.isfile(url):
            context_id = create_input_source(url).getPublicId()
            last_vocab_mtime = self.mtime_map.get(url)
            vocab_mtime = os.stat(url).st_mtime
            if not last_vocab_mtime or last_vocab_mtime < vocab_mtime:
                logger.debug("Parse file: '%s'", url)
                self.mtime_map[url] = vocab_mtime
                # use CG as workaround for json-ld always loading as dataset
                graph = ConjunctiveGraph()
                graph.parse(src, format=guess_format(src))
                self.graph.remove_context(context_id)
                for s, p, o in graph:
                    self.graph.add((s, p, o, context_id))
                return graph
        else:
            context_id = url

        if any(self.graph.triples((None, None, None), context=context_id)):
            logger.debug("Using context <%s>" % context_id)
            return self.graph.get_context(context_id)

        cache_path = self.get_fs_path(url)
        if os.path.exists(cache_path):
            logger.debug("Load local copy of <%s> from '%s'", context_id, cache_path)
            return self.graph.parse(cache_path, format='turtle', publicID=context_id)
        else:
            logger.debug("Fetching <%s> to '%s'", context_id, cache_path)
            graph = self.graph.parse(src,
                    format='rdfa' if url.endswith('html') else None)
            with open(cache_path, 'w') as f:
                graph.serialize(f, format='turtle')
            return graph

    def get_fs_path(self, url):
        return os.path.join(self.cachedir, quote(url, safe="")) + '.ttl'
开发者ID:niklasl,项目名称:vim-rdf,代码行数:48,代码来源:rdfns.py


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