0

I have this function:

`def get_author_books():
    sparql = SPARQLWrapper('https://dbpedia.org/sparql')
    sparql.setQuery("""
    SELECT distinct ?s ?author
    WHERE{ ?s rdf:type dbo:Book .
    ?s rdfs:label ?bookLabel . 
      FILTER(LANGMATCHES(LANG(?bookLabel), 'en')) 

    ?s dbo:author ?author . 
    ?author rdfs:label ?authorLabel . 
      FILTER(LANGMATCHES(LANG(?authorLabel), 'en')) 
    ?authorLabel bif:contains "St" 
    OPTIONAL {{ ?s dbp:country ?country .
              ?country rdfs:label ?countryLabel .
                 FILTER(LANGMATCHES(LANG(?countryLabel), 'en')) }}
    OPTIONAL {{ ?s dbo:literaryGenre ?genre .
              ?genre rdfs:label ?genreLabel .
                 FILTER(LANGMATCHES(LANG(?genreLabel), 'en')) }}
    OPTIONAL {{ ?s dbp:language ?language .
              ?language rdfs:label ?languageLabel .
                 FILTER(LANGMATCHES(LANG(?languageLabel), 'en')) }}
    } """)

    sparql.setReturnFormat(JSON)
    qres = sparql.query().convert()
    info = []
    for i in range(len(qres)):
        result = qres['results']['bindings'][i]
        author, book = (result['author']['value']).split('/')[-1], (result['s']['value']).split('/')[-1]
        info.append((author, book))
    print(info)
    print(len(qres))
    return info`

when I run the code I only get 2 results : [('Lucia_St._Clair_Robson', 'Ride_the_Wind'), ('Lucia_St._Clair_Robson', 'Fearless,_A_Novel_of_Sarah_Bowman')] 2 . While, in reality, the query has more than 20 results...appreciate your help

  • The advice on your previous question applies: start with a simpler query, see if it performs as expected, then move part of the query back in until the unexpected happens. – AndyS Nov 21 '22 at 12:19
  • I discovered that len(qres) returns 2 not the actual length of the structure. Are there any solutions for this issue? – Mohammed Esam Nov 21 '22 at 16:04
  • It is often helpful to express the details now in your tags, also in the body of your question, including versions of as many of the components under your control as possible, particularly as this seems likely to be a bug. (In this case, the versions of Python and SparqlWrapper are certainly relevant. The host OS name and version may also be relevant.) – TallTed Nov 21 '22 at 22:27
  • why are you iterating the JSON object by length instead of iterating the bindings? Obviously, the length of the JSON is not the same as the length of the bindings array. Use something like `for result in qres["results"]["bindings"]:` and then also please use the labels that you queried instead of splitting the URIs. So why are you not selecting the labels in your SPARQL query? That would give you the human-readable form – UninformedUser Nov 22 '22 at 06:41

0 Answers0