Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate Wikidata query in python

I am currently using Wikidata Query Service to run my Wikidata queries.

For example, one of my Wikidata queries looks as follows.

SELECT ?sLabel {
    SERVICE wikibase:mwapi {
        bd:serviceParam wikibase:api "EntitySearch".
        bd:serviceParam wikibase:endpoint "www.wikidata.org".
        bd:serviceParam mwapi:search "natural language processing".
        bd:serviceParam mwapi:language "en".
        ?item wikibase:apiOutputItem mwapi:item.
        ?num wikibase:apiOrdinal true.
    }
    ?s wdt:P279|wdt:P31 ?item .
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
ORDER BY ?num
LIMIT 10

I would like to know if we can use these queries in a python program? If so, how can we integrate the queries in python?

I am happy to provide more details if needed.

like image 232
EmJ Avatar asked May 02 '19 23:05

EmJ


People also ask

How do you use wikidata query service?

In the query.wikidata.org query editor, you can press Ctrl + Space (or Alt + Enter or Ctrl + Alt + Enter ) at any point in the query and get suggestions for code that might be appropriate; select the right suggestion with the up / down arrow keys, and press Enter to select it.

How do I get data from wikidata?

You can query the data in Wikidata through our SPARQL endpoint, the Wikidata Query Service. The service can be used both as an interactive web interface, or programmatically by submitting GET or POST requests to https://query.wikidata.org/sparql .

How do I use Sparql in Python?

To use as a command line script, you will need to install SPARQLWrapper and then a command line script called rqw (spaRQl Wrapper) will be available within the Python environment into which it is installed. run $ rql -h to see all the script's options.


2 Answers

In case you want to do it without a SPARQL specific library:

import requests

url = 'https://query.wikidata.org/sparql'
query = '''
SELECT ?item ?itemLabel ?linkcount WHERE {
    ?item wdt:P31/wdt:P279* wd:Q35666 .
    ?item wikibase:sitelinks ?linkcount .
FILTER (?linkcount >= 1) .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" . }
}
GROUP BY ?item ?itemLabel ?linkcount
ORDER BY DESC(?linkcount)
'''
r = requests.get(url, params = {'format': 'json', 'query': query})
data = r.json()
like image 166
Abbe Avatar answered Oct 02 '22 13:10

Abbe


sparqlwrapper can handle that. You can find more information here

like image 38
Alassane Ndiaye Avatar answered Oct 02 '22 12:10

Alassane Ndiaye