0

I am pretty new with SPARQL query using python package SPARQLWrapper. I was trying to retrieve the results from the DBpedia using following query:

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX type: <http://dbpedia.org/class/yago/>
PREFIX prop: <http://dbpedia.org/property/>

SELECT ?s ?p
WHERE {    
    ?country a type:LandlockedCountries ;
             rdfs:label ?s ;
             prop:populationEstimate ?p .
    FILTER (?p > 15000000) .
}

My code written with Python 2.7 is as follows:

from SPARQLWrapper import SPARQLWrapper, JSON, POST
import sys

def main(argv):     
    endpoint = str("http://dbpedia.org/sparql") 
    # QUERY as mentioned above 
    query = str(QUERY)    
    query = query.replace("__oc__","{")
    query = query.replace("__ob__","[")
    query = query.replace("__cc__","}")
    query = query.replace("__cb__","]")
    query = query.replace("__cr__"," ")
    query = query.replace("__cn__"," ")
    print "Parsed Query: " + query
    sparql = SPARQLWrapper(endpoint)
    sparql.setQuery(query)
    sparql.setMethod(POST)
    sparql.setReturnFormat(JSON)
    results = sparql.query().convert()   
    render = str("html")

    if render == "html":
        html_render(results)
    else:
        tab_render(results)

def html_render(results):

    for result in results["results"]["bindings"]:
        print result["s"]["value"], result["p"]["value"]

def tab_render(results):

    for result in results["results"]["bindings"]:
        print result["s"]["value"], result["p"]["value"]

if __name__ == '__main__':
        main(sys.argv)

I am suppose to receive the name of a bunch of country name and it's population. However, I am getting only one result that is:

Afghanistan 31822848

Am I doing something wrong? Any kind of help would be highly appreciated.

David
  • 33
  • 1
  • 2
  • 9
  • According to the SPARQLWrapper docs at https://rdflib.github.io/sparqlwrapper/doc/latest/ there may be an issue with using POST and JSON. Might be worth trying as a GET. – chrisis Mar 04 '16 at 10:38
  • Hi chrisis, thanks for your comment. Actually, the problem is that I am getting the expected results with either POST or GET when I am running this Python script from the Python editor (i.e. PyCharm) or even from the command line on Windows 7 environment. However, when I am trying the same code on Ubuntu 14.04 terminal or Python editor or shell script, I am getting only one Country and population pair. Please note I have tried both GET and POST methods. – David Mar 05 '16 at 18:59
  • What's the purpose of those [ `query = query.replace("__oc__","{")` ] replace statements? I've found myself able to send queries direct without any of that string-manipulation you've done there. Is it a dbpedia specific thing perhaps? – Thomas Kimber Aug 05 '16 at 03:48

0 Answers0