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


Python ConjunctiveGraph.query方法代码示例

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


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

示例1: validate_sparql_endpoint

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
def validate_sparql_endpoint(form, field):
    try:
        g = ConjunctiveGraph('SPARQLStore')
        g.open(field.data)
        g.query('SELECT * WHERE { ?s ?p ?o } LIMIT 1')
    except:
        raise ValidationError('This is not a valid SPARQL endpoint.')
开发者ID:jonlazaro,项目名称:linked-tag-world,代码行数:9,代码来源:forms.py

示例2: __init__

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
    def __init__(self, raw_result):

        rdf = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
        c = Namespace("http://s.opencalais.com/1/pred/")
        g = Graph()
        self.graph = g

        g.parse(StringIO(raw_result.decode('utf-8').encode('utf-8')))

        self.categories = [row for row in g.query(CATEGORY_QUERY["SPARQL"])]
        self.entities = [row for row in g.query(ENTITY_QUERY["SPARQL"])]
开发者ID:ThomasCabrol,项目名称:python-calais,代码行数:13,代码来源:calais-rdf.py

示例3: FOAF

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
class FOAF(callbacks.Privmsg):

    DATAFILE = "/var/www/rc98.net/zoia.rdf"

    def __init__(self, irc):
        self.g = Graph()
        #      self.g.parse('http://rc98.net/zoia.rdf')
        self.g.parse(self.DATAFILE, format="xml")
        self.uri = rdflib.URIRef("http://www.code4lib.org/id/zoia")
        self.FOAF = Namespace("http://xmlns.com/foaf/0.1/")
        super(callbacks.Plugin, self).__init__(irc)

    def _uri_of_user(self, nick):
        result = self.g.query(
            """
          PREFIX foaf: <http://xmlns.com/foaf/0.1/> 
          SELECT ?uri WHERE 
          {<http://www.code4lib.org/id/zoia> foaf:knows ?uri . ?uri foaf:nick ?nick .}
          """,
            initBindings={"nick": nick},
        )
        if len(result) > 0:
            userURI = list(result)[0][0]
            return userURI
        else:
            return None

    def _user_graph(self, uri):
        userGraph = Graph()
        try:
            userGraph.parse(uri)
        except Exception, e:
            u = "http://www.w3.org/2007/08/pyRdfa/extract?space-preserve=true&uri=" + uri
            userGraph.parse(u, identifier=uri)
        return userGraph
开发者ID:sylvar,项目名称:supybot-plugins,代码行数:37,代码来源:plugin.py

示例4: get_all_measurement_types

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
def get_all_measurement_types(ontology_file):
    graph = ConjunctiveGraph()
    graph.load(ontology_file, format="n3")
    query_str = '''SELECT DISTINCT ?mt ?label ?comment ?defn
        WHERE {
          ?mt rdfs:label ?label .
          ?mt rdfs:subClassOf <%s> .
          ?mt rdfs:subClassOf ?r1 .
          ?r1 owl:onProperty oboe:measuresEntity ; owl:someValuesFrom ?ent .
          ?mt rdfs:subClassOf ?r2 .
          ?r2 owl:onProperty oboe:measuresCharacteristic ; owl:someValuesFrom ?char .
          OPTIONAL { ?mt rdfs:comment ?comment }
          OPTIONAL { ?mt skos:definition ?defn }
        }''' % (MeasurementType)
    qres = list(graph.query(query_str, initNs=dict(oboe=URIRef("http://ecoinformatics.org/oboe/oboe.1.2/oboe-core.owl#"),
                                                   owl=OWL,rdfs=RDFS,skos=SKOS)))
    if len(qres) > 0:
        qres.sort(key=lambda x: x[0], reverse=True)
        result = dict()
        i = 0
        for row in qres:
            result[i] = {'uri' : row[0], 'label' : row[1], 'comment' : row[2], 'defn' : row[3]}
            i = i + 1
        print "Sparql query finished!"
        return result
    return None
开发者ID:tetherless-world,项目名称:linkipedia,代码行数:28,代码来源:AutoAnnotate_CNN_Character_Similarity.py

示例5: test_dSet_parsed_as_context_returns_results

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

示例6: _construct

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

示例7: test_flowcells_index_rdfa

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
    def test_flowcells_index_rdfa(self):
        model = ConjunctiveGraph()

        response = self.client.get(reverse('flowcell_index'))
        self.assertEqual(response.status_code, 200)
        model.parse(data=smart_text(response.content), format='rdfa')

        add_default_schemas(model)
        inference = Infer(model)
        errmsgs = list(inference.run_validation())
        self.assertEqual(len(errmsgs), 0, errmsgs)

        body =  """prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        prefix libns: <http://jumpgate.caltech.edu/wiki/LibraryOntology#>

        select ?flowcell
        where {
           ?flowcell a libns:IlluminaFlowcell .
        }"""
        bindings = set(['flowcell'])
        count = 0
        for r in model.query(body):
            count += 1

        self.assertEqual(count, len(FlowCell.objects.all()))
开发者ID:detrout,项目名称:htsworkflow,代码行数:27,代码来源:test_experiments.py

示例8: Config

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
class Config(object):
    def __init__(self, masterGraph, hubHost):
        self.etcd = etcd3.client(host=hubHost, port=9022)

        self.masterGraph = masterGraph
        self.hubHost = hubHost
        self.configGraph = ConjunctiveGraph()
        self.boards = []
        self.etcPrefix = 'pi/'

        self.reread()

        deferToThread(self.watchEtcd)

    def watchEtcd(self):
        events, cancel = self.etcd.watch_prefix(self.etcPrefix)
        reactor.addSystemEventTrigger('before', 'shutdown', cancel)
        for ev in events:
            log.info('%s changed', ev.key)
            reactor.callFromThread(self.configChanged)

    def configChanged(self):
        self.cancelRead()
        self.rereadLater = reactor.callLater(.1, self.reread)

    def cancelRead(self):
        if getattr(self, 'rereadLater', None):
            self.rereadLater.cancel()
        self.rereadLater = None

    @STATS.configReread.time()
    def reread(self):
        self.rereadLater = None
        log.info('read config')
        self.configGraph = ConjunctiveGraph()
        for v, md in self.etcd.get_prefix(self.etcPrefix):
            log.info('  read file %r', md.key)
            self.configGraph.parse(StringInputSource(v), format='n3')
        self.configGraph.bind('', ROOM)
        self.configGraph.bind('rdf', RDF)
        # config graph is too noisy; maybe make it a separate resource
        #masterGraph.patch(Patch(addGraph=self.configGraph))
        self.setupBoards()
        
    def setupBoards(self):       
        thisHost = Literal(hostname)
        for row in self.configGraph.query(
                'SELECT ?board WHERE { ?board a :PiBoard; :hostname ?h }',
                initBindings=dict(h=thisHost)):
            thisBoard = row.board
            break
        else:
            log.warn("config had no board for :hostname %s. Waiting for config update." %
                     thisHost)
            self.boards = []
            return

        log.info("found config for board %r" % thisBoard)
        self.boards = [Board(self.configGraph, self.masterGraph, thisBoard, self.hubHost)]
        self.boards[0].startPolling()
开发者ID:drewp,项目名称:homeauto,代码行数:62,代码来源:piNode.py

示例9: TestSparqlJsonResults

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

    def setUp(self):
        self.graph = ConjunctiveGraph()
        self.graph.parse(StringIO(test_data), format="n3")

    def test_base_ref(self):
        rt=self.graph.query(test_query).serialize("python")
        self.failUnless(rt[0] == Literal("Alice"),"Expected:\n 'Alice' \nGot:\n %s" % rt)
开发者ID:AuroraSkywalker,项目名称:watchdog,代码行数:11,代码来源:test_sparql_base_ref.py

示例10: runTest

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
    def runTest(self):
        """Run the specified task force test."""
        import rdfadict
        import rdfadict.sink.graph

        print self._uri

        # set up our target sink
        g = Graph()
        sink = rdfadict.sink.graph.GraphSink(g)

        # run rdfadict over the input
        parser = rdfadict.RdfaParser()
        parser.parseurl(self._source, sink)
        
        # execute the test SPARQL
        g.query(self._result)

        print g.selected
开发者ID:cc-archive,项目名称:rdfadict,代码行数:21,代码来源:test_taskforce.py

示例11: TestSparqlOPT_FILTER2

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
class TestSparqlOPT_FILTER2(unittest.TestCase):
    def setUp(self):
        self.graph = ConjunctiveGraph()
        self.graph.load(StringIO(testContent), format='n3')
    def test_OPT_FILTER(self):
        results = self.graph.query(QUERY,
                                   DEBUG=False)
        results = list(results)
        self.failUnless(
            results == [(doc1,)],
            "expecting : %s .  Got: %s"%([(doc1,)],repr(results)))
开发者ID:pombredanne,项目名称:rdfextras,代码行数:13,代码来源:test_sparql_naf2.py

示例12: test_simple_recursion

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
 def test_simple_recursion(self):
     graph = ConjunctiveGraph()
     graph.load(StringIO(BASIC_KNOWS_DATA), format='n3')
     results = graph.query(KNOWS_QUERY,
                           processor="sparql", 
                           DEBUG=False)
     results = set(results)
     person1 = URIRef('ex:person.1')
     person2 = URIRef('ex:person.2')
     nose.tools.assert_equal(
       results,
       set([(person1, None), (person1, Literal('person 3')),
            (person2, Literal('person 3'))]))
开发者ID:RDFLib,项目名称:rdfextras,代码行数:15,代码来源:test_sparql_recurse.py

示例13: TestSPARQLFilters

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
class TestSPARQLFilters(unittest.TestCase):
    debug = False
    sparql = True
    
    def setUp(self):
        NS = u"http://example.org/"
        self.graph = ConjunctiveGraph()
        self.graph.parse(data=testgraph, format="n3", publicID=NS)

    def testSPARQLNotEquals(self):
        rt = self.graph.query(testquery, initNs={'rdf': RDF.uri}, DEBUG=False)
        for row in rt:
            assert str(row[0]) == "http://example.org/bar" #, "unexpected item of '%s'" % repr(row[0])
开发者ID:RDFLib,项目名称:rdfextras,代码行数:15,代码来源:test_not_equals.py

示例14: JSON

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

    def setUp(self):
        self.graph = ConjunctiveGraph(plugin.get('IOMemory',Store)())
        self.graph.parse(StringIO(test_data), format="n3")
        
    def testComma(self):
        """
        Verify the serialisation of the data as json contains an exact
        substring, with the comma in the correct place.
        """
        results = self.graph.query(test_query)
        result_json = results.serialize(format='json')
        self.failUnless(result_json.find(correct) > 0)

    def testHeader(self):
        """
        Verify that the "x", substring is omitted from the serialised output.
        """
        results = self.graph.query(test_header_query)
        result_json = results.serialize(format='json')
        self.failUnless(result_json.find('"x",') == -1)
开发者ID:RDFLib,项目名称:rdfextras,代码行数:24,代码来源:JSON.py

示例15: _DBPediaMixin

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import query [as 别名]
class _DBPediaMixin(object):
    def __init__(self):
        self.graph = ConjunctiveGraph('SPARQLStore')

    def _get_media_api_host(self, language):
        return language + u'.wikipedia.org'

    def _get_dbpedia_url(self, language):
        return u'http://' +('' if language == u'en' else language + u'.') + u'dbpedia.org'

    def _fetch_dbpedia_query_result(self, query):
        result = self.graph.query( unicode(query) )
        return_fetch_results = [ [ unicode(e.n3()) if (not e is None) else ''  for e in fetch_result] for fetch_result in result ]
        return return_fetch_results
开发者ID:yustoris,项目名称:wikipedia_searcher,代码行数:16,代码来源:dbpedia_mixin.py


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