1 year ago
#377993
JakeGov
Wikidata SPARQL query has different results in Python
If I go on https://query.wikidata.org/ and execute this query (made with the Wikidata query builder):
SELECT DISTINCT ?item ?itemLabel WHERE {
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
{
SELECT DISTINCT ?item WHERE {
?item p:P31 ?statement0.
?statement0 (ps:P31/(wdt:P279*)) wd:Q28575.
?item p:P17 ?statement1.
?statement1 (ps:P17/(wdt:P279*)) wd:Q145.
}
LIMIT 100
}
}
I get this output:
Essentially, this query is finding counties in the United Kingdom.
Now when I execute this query in Python:
# pip install sparqlwrapper
# https://rdflib.github.io/sparqlwrapper/
import sys
from SPARQLWrapper import SPARQLWrapper, JSON
endpoint_url = "https://query.wikidata.org/sparql"
query = """
SELECT DISTINCT ?item ?itemLabel WHERE {
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
{
SELECT DISTINCT ?item WHERE {
?item p:P31 ?statement0.
?statement0 (ps:P31/(wdt:P279*)) wd:Q28575.
?item p:P17 ?statement1.
?statement1 (ps:P17/(wdt:P279*)) wd:Q145.
}
LIMIT 100
}
}"""
def get_results(endpoint_url, query):
user_agent = "WDQS-example Python/%s.%s" % (sys.version_info[0], sys.version_info[1])
# TODO adjust user agent; see https://w.wiki/CX6
sparql = SPARQLWrapper(endpoint_url, agent=user_agent)
sparql.setQuery(query)
sparql.setReturnFormat(JSON)
return sparql.query().convert()
results = get_results(endpoint_url, query)
for result in results["results"]["bindings"]:
print(result)
I get this output:
{'item': {'type': 'uri', 'value': 'http://www.wikidata.org/entity/Q100166'}, 'itemLabel': {'type': 'literal', 'value': 'Q100166'}}
{'item': {'type': 'uri', 'value': 'http://www.wikidata.org/entity/Q109128'}, 'itemLabel': {'type': 'literal', 'value': 'Q109128'}}
{'item': {'type': 'uri', 'value': 'http://www.wikidata.org/entity/Q156150'}, 'itemLabel': {'type': 'literal', 'value': 'Q156150'}}
{'item': {'type': 'uri', 'value': 'http://www.wikidata.org/entity/Q166803'}, 'itemLabel': {'type': 'literal', 'value': 'Q166803'}}
{'item': {'type': 'uri', 'value': 'http://www.wikidata.org/entity/Q189592'}, 'itemLabel': {'type': 'literal', 'value': 'Q189592'}}
{'item': {'type': 'uri', 'value': 'http://www.wikidata.org/entity/Q190678'}, 'itemLabel': {'type': 'literal', 'value': 'Q190678'}}
Rather than getting the name of the county in the itemLabel, I get the Q number. I want the itemLabel to show the names of the counties, as in the screenshot above.
What is going wrong?
sparql
wikipedia
wikidata
0 Answers
Your Answer