Created
April 16, 2018 13:05
-
-
Save pierric/8bf4a95189dddea838cd250f2b0a79fe to your computer and use it in GitHub Desktop.
Get a random article from the dbpedia
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from SPARQLWrapper import SPARQLWrapper, JSON | |
import requests | |
from urllib.request import unquote | |
# PREFIX dbpedia-owl: <http://dbpedia.org/ontology/> | |
# PREFIX dbpprop: <http://dbpedia.org/property/> | |
# PREFIX dbres: <http://dbpedia.org/resource/> | |
# | |
# SELECT ?abstract WHERE { | |
# dbres:Abijah_Beckwith_(Wisconsin) dbpedia-owl:abstract ?abstract. | |
# } | |
def abstract(name): | |
sparql = SPARQLWrapper("http://dbpedia.org/sparql") | |
sparql.setQuery(""" | |
PREFIX dbpedia-owl: <http://dbpedia.org/ontology/> | |
PREFIX dbpprop: <http://dbpedia.org/property/> | |
PREFIX dbres: <http://dbpedia.org/resource/> | |
SELECT ?abstract WHERE {{ | |
<http://dbpedia.org/resource/{}> dbpedia-owl:abstract ?abstract. | |
FILTER langMatches(lang(?abstract),"en") | |
}}""".format(name)) | |
sparql.setReturnFormat(JSON) | |
results = sparql.query().convert() | |
bindings = results["results"]["bindings"] | |
if bindings: | |
return bindings[0]["abstract"]["value"] | |
else: | |
return None | |
res = requests.get('https://en.wikipedia.org/wiki/Special:Random') | |
# res.url is the redirected url | |
# we just extract the page name from there, and start the SPARQL | |
resname = res.url.split('/')[-1] | |
abst = abstract(unquote(resname)) | |
if abst: | |
print(abst) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment