0

这是我的代码

#!/usr/bin/python
# -*- coding: utf-8 -*-

import requests
from requests.auth import HTTPBasicAuth
from abc import ABCMeta, abstractmethod

class PPTSparqlClient:

    """Minimal Class to access PPT SparqlEndpoints"""

    def __init__(self, endpoint, user, passw):
        self.endpoint = endpoint;
        self.user = user;
        self.passw = passw;
        self.defaultHeaders = { "accept":"application/sparql-results+json" }
        self.defaultAuth = HTTPBasicAuth(self.user, self.passw)

    def execute(self, query, handler=None):
        r = requests.get(self.endpoint, auth=self.defaultAuth, headers=self.defaultHeaders, params={"query":query})
        if (r.status_code==404):
            raise Exception("404 : not found " + self.endpoint);        
        if (r.status_code==401):
            raise Exception("401 : unauthorized " + self.user + " " + self.passw)
        if(handler==None):
            return r.json();
        else:
            j = r.json();
            handler.startQueryResult(j["head"]["vars"]);
            for bindingSet in j["results"]["bindings"]:
                handler.handleSolution(bindingSet);
            handler.endQueryResult();

class TupleQueryResultHandler:

    """Base Class of SPARQL SELECT Query handlers"""

    @abstractmethod
    def startQueryResult(self,heads):
        pass;
    @abstractmethod
    def handleSolution(self,bindingSet):
        pass;
    @abstractmethod
    def endQueryResult(self):
        pass;        

class TerminalPrinter(TupleQueryResultHandler):

    """Class to handle application/sparql-results+json results by printing them to the terminal"""    

    def startQueryResult(self,heads):
        self.heads = heads;
        for head in heads:
            print "binding:"+head;
        print ""

    def handleSolution(self,bindingSet):
        for head in self.heads:
            print head+":"+bindingSet[head]["value"];
        print "";



def main(endpoint, user, passw, query):
    client = PPTSparqlClient(endpoint,user,passw);
    try:
        client.execute(query, TerminalPrinter());
    except Exception as ex:
        print ex.message


endpoint = "http://termmanagement.poolparty.biz/PoolParty/sparql/LawEnforcementSmall";
user = "username";
passw = "pass";

if  __name__ =='__main__':
    main(endpoint,user,passw,"SELECT * WHERE { ?s ?p ?o } LIMIT 10")

这是我得到的输出:

binding:s
binding:p
binding:o

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://www.w3.org/1999/02/22-rdf-syntax-ns#type
o:http://rdfs.org/ns/void#Dataset

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://purl.org/dc/terms/creator
o:doanem

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://purl.org/dc/terms/language
o:en

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://www.semantic-web.at/ppcl/availablelanguages
o:en

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://purl.org/dc/terms/date
o:2015-01-27T16:28:21Z

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://purl.org/dc/terms/subject
o:video management

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://purl.org/dc/terms/title
o:Law Enforcement

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://rdfs.org/ns/void#sparqlEndpoint
o:http://termmanagement.poolparty.biz/PoolParty/sparql/LawEnforcement

s:http://termmanagement.poolparty.biz/LawEnforcementSmall
p:http://rdfs.org/ns/void#feature
o:node19dtn3sgfx1

s:node19dtn3sgfx1
p:http://www.w3.org/1999/02/22-rdf-syntax-ns#type
o:http://rdfs.org/ns/void#TechnicalFeature

如何将文件转换为 JSON 格式以进行进一步分析?我读过有一个内置的方法可以从 SPARQL 转换为 JSON。我怎样才能做到这一点?

4

2 回答 2

0

嗯,我想通了!

我只需要使用 json.dumps(json query,filename) 以 JSON 格式输出!

于 2015-03-20T15:52:40.357 回答
0

我强烈建议使用SPARQLWrapper而不是尝试自己实现发出正确 SPARQL 请求的所有细节。例如,您的 SPARQL 端点可能不会“说话” application/sparql-results+json。SPARQLWrapper 会为您正确处理这个问题。

于 2015-05-06T13:39:30.007 回答