• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sparql.prepareQuery函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中rdflib.plugins.sparql.prepareQuery函数的典型用法代码示例。如果您正苦于以下问题:Python prepareQuery函数的具体用法?Python prepareQuery怎么用?Python prepareQuery使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: rewriteQueryToCapabilityMap

def rewriteQueryToCapabilityMap(q):
	# Note, for debugging, use: algebra.pprintAlgebra(<node?>) 

	# Navigate to BGP node in tree
	prologue_ = []
	for prefix, uri in q.prologue.namespace_manager.namespaces():
		prologue_.append("PREFIX %s: <%s>" % (prefix, uri,))

	capabilityServiceMappings = [ ('http://froogle.com/', algebra.Join( algebra.BGP([( Variable('a'), Variable('a'), Variable('a'))]), algebra.BGP([( Variable('b'), Variable('b'), Variable('b'))]))), ]

	addServiceCapabilities(q.algebra, capabilityServiceMappings)
	query_ = evalPart(q.prologue, q.algebra)

	
	#print "\n".join(prologue_)
	print query_
	#			ServiceGraphPattern(
    #                    term = http://fish.db.endpoint
    #                    graph = GroupGraphPatternSub(
    #                        part = [TriplesBlock_{'_vars': set([?dbp]), 'triples': [[?dbp, rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.term.Literal(u'fish')]]}]
    #                        _vars = set([?dbp])
    #                        )
    #                    _vars = set([?dbp])
    #                    )
	try:
		prepareQuery("\n".join(prologue_) + query_, initNs = initNS)
	except:
		print '## Did not validate ##'
开发者ID:bgreenwood,项目名称:research_project,代码行数:28,代码来源:experiment_harness.py


示例2: parse

def parse(foaf_url):
    global gexf_graph
    global parsedFOAFS
    global queuedFOAFS

    g = Graph()

    try:
        g.load(foaf_url)
    except Exception:
        print "Can't fetch " + foaf_url
        return

    SIOC = Namespace("http://rdfs.org/sioc/ns#")

    acctID = URIRef(g.value(URIRef(foaf_url), FOAF.maker) + "#acct")
    root_accountName = str(g.value(acctID, FOAF.accountName))
    root_webfinger = root_accountName + "@" + urlparse(foaf_url).hostname

    subscriptions = prepareQuery(
        """SELECT ?accountName ?accountProfilePage
           WHERE {
              ?person sioc:follows ?b .
              ?b foaf:accountName ?accountName .
              ?b foaf:accountProfilePage ?accountProfilePage .
           }""",
        initNs = { "foaf": FOAF, "sioc": SIOC })

    subscribers = prepareQuery(
        """SELECT ?accountName ?accountProfilePage
           WHERE {
              ?b sioc:follows ?person .
              ?b foaf:accountName ?accountName .
              ?b foaf:accountProfilePage ?accountProfilePage .
           }""",
        initNs = { "foaf": FOAF, "sioc": SIOC })

    gexf_graph.addNode(root_webfinger, root_webfinger)

    for subscription in g.query(subscriptions, initBindings={'person': acctID}):
        accountProfilePage = str(subscription.accountProfilePage) + "/foaf"
        accountName = str(subscription.accountName)
        if (blacklisted(accountProfilePage) is False):
            hostname = urlparse(accountProfilePage).hostname
            webfinger = accountName + "@" + hostname
            gexf_graph.addNode(webfinger, webfinger)
            gexf_graph.addEdge(root_webfinger + webfinger, root_webfinger, webfinger)
            if accountProfilePage not in parsedFOAFS:
                queuedFOAFS.put(accountProfilePage)

    for subscriber in g.query(subscribers, initBindings={'person': acctID}):
        accountProfilePage = str(subscriber.accountProfilePage) + "/foaf"
        accountName = str(subscriber.accountName)
        if (blacklisted(accountProfilePage) is False):
            hostname = urlparse(accountProfilePage).hostname
            webfinger = accountName + "@" + hostname
            gexf_graph.addNode(webfinger, webfinger)
            gexf_graph.addEdge(webfinger + root_webfinger, root_webfinger, webfinger)
            if accountProfilePage not in parsedFOAFS:
                queuedFOAFS.put(accountProfilePage)
开发者ID:chimo,项目名称:graph-the-feds,代码行数:60,代码来源:graph.py


示例3: find_filenames_for_tags

    def find_filenames_for_tags(self, tags, flag_only_existing=False):
        dinst_set = self.find_datainstances_for_tags(tags)
        print(dinst_set)
        g = Graph()
        for dinst in dinst_set:
            g.parse(self.client.target('observation/data-about?urn=' + dinst))
        filepaths = {}
        for dinst in dinst_set:
            queryDataInstance = prepareQuery("""
                SELECT DISTINCT ?filepath ?dataobject
                WHERE {
                    ?dataInstance fff:dataObject ?dataobject .
                    ?dataInstance fff:dataLocation ?dataLocation .
                    ?dataLocation fff:filePath ?filepath .
                }""", initNs=ns)
            queryDataObject = prepareQuery(
                """
                SELECT ?tag
                WHERE {
                    ?anno oa:hasTarget ?dataobject .
                    ?anno oa:hasBody ?body .
                    ?body cnt:chars ?tag .
                }""", initNs=ns)

            queryDataInstance
            dinst_uri = URIRef(dinst)
            filepath = ""
            tags = set()
            for row in g.query(queryDataInstance, initBindings=dict(dataInstance=dinst_uri)):
                try:
                    row['filepath']
                    fp = row['filepath'].value
                    filepath = fp
                    print fp
                except KeyError:
                    pass
                try:
                    dataobject = "" + row['dataobject']
                    g.parse(self.client.target("observation/data-about?urn=" + dataobject))
                    # print len(g)
                    for row2 in g.query(queryDataObject, initBindings=dict(dataobject=dataobject)):
                        try:
                            row2['tag']
                            tag = row2['tag'].value
                            tags.add(tag)
                        except KeyError:
                            pass
                except KeyError:
                    pass
        # if (flag_only_existing and os.path.exists(filepath)):
        #     filepaths[filepath] = tags
        # else:
            filepaths[filepath] = tags

        return filepaths
开发者ID:kba,项目名称:fff,代码行数:55,代码来源:tag.py


示例4: add_prepared_query

    def add_prepared_query(self, name, query, initNs=None):
        self.log.debug("adding prepared query with name %s", name)
        pq = lambda x,y: prepareQuery(x, initNs=y)
        if initNs is None:
            pq = lambda x,y: prepareQuery(x)

        prepared_query = pq(query, initNs)
        self.prepared_queries[name] = (query, prepared_query)
        self.prepared_query_to_str[prepared_query] = query

        return self.prepared_queries[name][-1]
开发者ID:algrebe,项目名称:sdo-server,代码行数:11,代码来源:sdoserver.py


示例5: __init__

 def __init__(self, callback, sparql_query):
     """Creates a SPARQL filter for RDF triples."""
     if sparql_query.strip()[:3].lower() != 'ask':
         raise ZtreamyException('Only ASK queries are allowed '
                                'in SPARQLFilter')
     super(SPARQLFilter, self).__init__(callback)
     self.query = prepareQuery(sparql_query)
开发者ID:jfisteus,项目名称:ztreamy,代码行数:7,代码来源:filters.py


示例6: test_dataset_description_linksets

    def test_dataset_description_linksets(self):
        res = self.client.get('/.well-known/void')
        self.assertEqual(res.status_code, http.client.OK)
        self.assertEqual(res.headers['Content-Type'], 'text/turtle')
        g = Graph()
        g.parse(format='turtle', data=res.get_data(as_text=True))
        # http://dbpedia.org/void/Dataset
        q = sparql.prepareQuery('''
SELECT ?triples
WHERE {
  ?linkset a void:Linkset .
  ?linkset void:subset <http://n2t.net/ark:/99152/p0d> .
  ?linkset void:subjectsTarget <http://n2t.net/ark:/99152/p0d> .
  ?linkset void:linkPredicate ?predicate .
  ?linkset void:objectsTarget ?dataset .
  ?linkset void:triples ?triples .
}
''', initNs={'void': VOID})
        dbpedia = URIRef('http://dbpedia.org/void/Dataset')
        triples = next(iter(g.query(
            q, initBindings={'dataset': dbpedia,
                             'predicate': DCTERMS.spatial})))['triples'].value
        self.assertEqual(triples, 3)

        worldcat = URIRef('http://purl.oclc.org/dataset/WorldCat')
        triples = next(iter(g.query(
            q, initBindings={'dataset': worldcat,
                             'predicate': DCTERMS.isPartOf})))['triples'].value
        self.assertEqual(triples, 1)
开发者ID:periodo,项目名称:periodo-server,代码行数:29,代码来源:test_representation.py


示例7: loadFragmentDefinitions

    def loadFragmentDefinitions(self, folder, fileName):
        datasets = {}
        self.fragments = {}
        with open (fileName, 'r') as f:
            for line in f:
                line = line.strip()
                ws = line.split()
                if (len(ws) > 0):
                    fragment = ws[0]
                    ds = ws[1]
                    datasets[fragment] = ds

        content = os.listdir(folder)
        self.viewsDefinition = {}
        for g in content:
            path = folder+'/'+g
            f = open(path)
            viewStr = f.read()
            f.close()
            view = prepareQuery(viewStr)
            t = getTriple(view)
            i = path.rfind('/') + 1
            j = path.rfind('.')
            j = len(path) if j < 0 else j
            name = path[i:j]
            ds = datasets[name]
            self.fragments[name] = TriplePatternFragment(t, ds)
开发者ID:gmontoya,项目名称:fedra,代码行数:27,代码来源:FedraSourceSelection.py


示例8: test_graph_prefix

def test_graph_prefix():
    """
    This is issue https://github.com/RDFLib/rdflib/issues/313
    """

    g1 = Graph()
    g1.parse(data="""
    @prefix : <urn:ns1:> .
    :foo <p> 42.
    """, format="n3")

    g2 = Graph()
    g2.parse(data="""
    @prefix : <urn:somethingelse:> .
    <urn:ns1:foo> <p> 42.
    """, format="n3")

    assert isomorphic(g1, g2)

    q_str = ("""
    PREFIX : <urn:ns1:>
    SELECT ?val
    WHERE { :foo ?p ?val }
    """)
    q_prepared = prepareQuery(q_str)

    expected = [(Literal(42),)]

    eq_(list(g1.query(q_prepared)), expected)
    eq_(list(g2.query(q_prepared)), expected)

    eq_(list(g1.query(q_str)), expected)
    eq_(list(g2.query(q_str)), expected)
开发者ID:drewp,项目名称:rdflib,代码行数:33,代码来源:test_sparql.py


示例9: testQuery

def testQuery():
    g = makeGraph()

    q = sparql.prepareQuery('SELECT ?o WHERE {?s schema:name ?o} LIMIT 20', initNs = { "schema": "http://schema.org/" })

    myquery = g.query(q)
    
    return myquery
开发者ID:HLITS,项目名称:remote_rdf_load_from_file,代码行数:8,代码来源:rdf_load_functionalized.py


示例10: validateSparql

	def validateSparql(self, text):
		''' validates a sparql query and stores it in a separate file '''
		text = str(text)
		
		try:
			return sparql.prepareQuery(text, initNs=self.namespaces)
		except Exception as error: 
			raise MalformedSparqlQueryError([str(type(error)), str(error), text])
开发者ID:lkastler,项目名称:Analysis-DbpediaLogs,代码行数:8,代码来源:SparqlValidator.py


示例11: timequery

def timequery(action):                                                              #time query function
    
    q = prepareQuery(
        'SELECT ?time WHERE { ?action alfred:takes ?time .}',
        initNs = { "alfred": "http://www.semanticweb.org/suv/ontologies/2015/3/alfredowl/"})
    
    this = parse + action
    for row in g.query(q, initBindings={'action': this}):
        return int(row.time)
开发者ID:suv-12,项目名称:AIProject,代码行数:9,代码来源:Sparqlquery.py


示例12: taskquery

def taskquery(action, tasks=[]):                                                    #tasks query function
    
    q = prepareQuery(
        'SELECT ?name WHERE { ?action alfred:involves ?task . ?task alfred:named ?name .}',
        initNs = { "alfred": "http://www.semanticweb.org/suv/ontologies/2015/3/alfredowl/"})
    
    this = parse + action
    for row in g.query(q, initBindings={'action': this}):
        print row.name
开发者ID:suv-12,项目名称:AIProject,代码行数:9,代码来源:Sparqlquery.py


示例13: moodquery

def moodquery(action):                                                              #mood query function
    
    q = prepareQuery(
        'SELECT ?name WHERE { ?action alfred:results ?mood . ?mood alfred:named ?name .}',
        initNs = { "alfred": "http://www.semanticweb.org/suv/ontologies/2015/3/alfredowl/"})
    
    this = parse + action
    for row in g.query(q, initBindings={'action': this}):
        return str(row.name)
开发者ID:suv-12,项目名称:AIProject,代码行数:9,代码来源:Sparqlquery.py


示例14: test_dataset_description

    def test_dataset_description(self):
        res1 = self.client.get(
            '/', headers={'Accept': 'text/html'}, buffered=True)
        self.assertEqual(res1.status_code, http.client.SEE_OTHER)
        self.assertEqual(urlparse(res1.headers['Location']).path,
                         '/index.json.html')

        res2 = self.client.get('/', headers={'Accept': 'text/turtle'})
        self.assertEqual(res2.status_code, http.client.OK)
        self.assertEqual(res2.headers['Content-Type'], 'text/turtle')

        res3 = self.client.get('/.well-known/void')
        self.assertEqual(res3.status_code, http.client.OK)
        self.assertEqual(res3.headers['Content-Type'], 'text/turtle')
        self.assertEqual(res3.get_data(as_text=True),
                         res2.get_data(as_text=True))

        res4 = self.client.get('/.wellknown/void')
        self.assertEqual(res4.status_code, http.client.OK)
        self.assertEqual(res4.headers['Content-Type'], 'text/turtle')
        self.assertEqual(res4.get_data(as_text=True),
                         res3.get_data(as_text=True))

        res5 = self.client.get('/.well-known/void.ttl')
        self.assertEqual(res5.status_code, http.client.OK)
        self.assertEqual(res5.headers['Content-Type'], 'text/turtle')
        self.assertEqual(res5.get_data(as_text=True),
                         res4.get_data(as_text=True))

        res6 = self.client.get('/.well-known/void.ttl.html')
        self.assertEqual(res6.status_code, http.client.OK)
        self.assertEqual(res6.headers['Content-Type'], 'text/html')

        g = Graph()
        g.parse(format='turtle', data=res2.get_data(as_text=True))
        self.assertIn(
            (PERIODO['p0d'], DCTERMS.provenance, HOST['h#changes']), g)
        desc = g.value(predicate=RDF.type, object=VOID.DatasetDescription)
        self.assertEqual(
            desc.n3(), '<http://n2t.net/ark:/99152/p0>')
        title = g.value(subject=desc, predicate=DCTERMS.title)
        self.assertEqual(
            title.n3(), '"Description of the PeriodO Period Gazetteer"@en')
        q = sparql.prepareQuery('''
SELECT ?count
WHERE {
  ?d void:classPartition ?p .
  ?p void:class ?class .
  ?p void:entities ?count .
}
''', initNs={'void': VOID, 'skos': SKOS})
        concept_count = next(iter(g.query(
            q, initBindings={'class': SKOS.Concept})))['count'].value
        self.assertEqual(concept_count, 3)
        scheme_count = next(iter(g.query(
            q, initBindings={'class': SKOS.ConceptScheme})))['count'].value
        self.assertEqual(scheme_count, 1)
开发者ID:periodo,项目名称:periodo-server,代码行数:57,代码来源:test_representation.py


示例15: is_inside

def is_inside(textplace,graph):
    """Returns true if the place defined as text is disambiguated in graph
    returns false otherwise"""
    askquery = prepareQuery(
            """ASK {?iri schema:jobLocation ?place .
                ?iri edsa:Location ?placeiri}""",
                initNs = {"schema" : ns.schema , 
                    "edsa" : ns.edsa})
    return bool(graph.query(askquery, initBindings={"place" : Literal(textplace)}))
开发者ID:edsa-project,项目名称:dashboard,代码行数:9,代码来源:geonames.py


示例16: actionquery

def actionquery(mood, actions=[]):                                                  #actions query function
    
    q = prepareQuery(
        'SELECT ?name WHERE { ?mood alfred:possible ?action . ?action alfred:named ?name .}',
        initNs = { "alfred": "http://www.semanticweb.org/suv/ontologies/2015/3/alfredowl/"})
    
    this = parse + mood
    for row in g.query(q, initBindings={'mood': this}):
        actions.append(row.name)
    return actions
开发者ID:suv-12,项目名称:AIProject,代码行数:10,代码来源:Sparqlquery.py


示例17: test_sparql_bnodelist

def test_sparql_bnodelist():
    """

    syntax tests for a few corner-cases not touched by the
    official tests.

    """

    prepareQuery('select * where { ?s ?p ( [] ) . }')
    prepareQuery('select * where { ?s ?p ( [ ?p2 ?o2 ] ) . }')
    prepareQuery('select * where { ?s ?p ( [ ?p2 ?o2 ] [] ) . }')
    prepareQuery('select * where { ?s ?p ( [] [ ?p2 ?o2 ] [] ) . }')
开发者ID:drewp,项目名称:rdflib,代码行数:12,代码来源:test_sparql.py


示例18: build_possible_queries

def build_possible_queries():
    queries = []
    query = prepareQuery("""SELECT ?name
        WHERE { ?r owl:Class ro:Recipe .
                ?r ro:name ?name . }
        ORDER BY ?name""", initNs={'ro': RO, 'owl': OWL})
    queries.append(Query('List all imported recipes', query))
    query = prepareQuery("""SELECT ?name
        WHERE { ?i owl:Class ro:Food .
                ?i ro:food_name ?name . }
        ORDER BY ?name""", initNs={'ro': RO, 'owl': OWL})
    queries.append(Query('List all imported ingredients', query))
    query = prepareQuery("""SELECT ?name
        WHERE { ?recipe ro:name ?name .
                ?recipe ro:ingredient ?ingredient .
                ?ingredient ro:food ?food .
                ?food ro:food_name ?param . }
        ORDER BY ?name""", initNs={'ro': RO, 'owl': OWL})
    queries.append(Query('List all recipes containing desired ingredient', query, 'Ingredient name: '))
    return queries
开发者ID:mc-suchecki,项目名称:Rextractor,代码行数:20,代码来源:query.py


示例19: delete

    def delete(self):
        query = prepareQuery(
            'delete { ?s ?p ?o } WHERE { ?person foaf:knows ?s .}',
            initNs={"foaf": FOAF})

        tim = rdflib.URIRef("http://www.w3.org/People/Berners-Lee/card#i")

        for row in self._graph.query(query, initBindings={'person': tim}):
            print row

        return query
开发者ID:mpetyx,项目名称:django-rdfGraph,代码行数:11,代码来源:rdfCRUD.py


示例20: queryQualityDataIds

 def queryQualityDataIds(self):
     
     query_str = """SELECT DISTINCT ?uri ?comment
        WHERE {
           ?uri """ + CMR_QA.NAMESPACE_PREFIX + """:"""+ CMR_QA.hasQualityComment_Name+ """ ?comment .
           ?uri rdf:type """ + CMR_QA.NAMESPACE_PREFIX + """:""" + CMR_QA.Cine_MRI_Quality_Data_Name + """ .
        }"""
     query_object = prepareQuery(query_str, initNs={CMR_QA.NAMESPACE_PREFIX : CMR_QA.BASE_URI})
        
     #print(query2)
 
     self.qualityDataURIComments = self.rdfgraph.query(query_object)
开发者ID:ernestojimenezruiz,项目名称:CMR-QA-Semantic-Layer,代码行数:12,代码来源:triple_extension.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python py3compat.b函数代码示例发布时间:2022-05-26
下一篇:
Python plugin.register函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap