how to convert wiki data QID to entity and vice versa in python

Viewed 33

i have list of entities which have been extracted from a text.

for example here is my text

"text": "Anarchism is an anti-authoritarian political and social philosophy that rejects hierarchies deemed unjust and advocates their replacement with self-managed, self-governed societies based on voluntary, cooperative institutions."

here is extracted entities from this text.(for each pair first one is entity and second one is its mention in text.

"anchored_et": [["Anti-authoritarianism", "anti-authoritarian"], ["Political philosophy", "political"], ["Social philosophy", "social philosophy"], ["Hierarchy", "hierarchies"], ["Workers' self-management", "self-managed"], ["Self-governance", "self-governed"], ["cooperative", "cooperative"]]

besides that i have list of triples which their subject and objects are in wiki data QID format.

so i need first to convert extracted entities to their QID then finding triples which their subject is like that and after finding these triples i need to convert object QID to its entity.

so i need to convert wiki data QID to entity and vice versa in python.

my question is how can i do that.

1 Answers

here is two functions which i wrote to do this for me .

i used SPARQLWrapper from pypi.

from SPARQLWrapper import SPARQLWrapper
import requests

def wikidata_id_to_enwiki_title(Qid):
    try:

        sparql = SPARQLWrapper("https://query.wikidata.org/sparql")
        sparql.setReturnFormat(JSON)

        sparql.setQuery('SELECT DISTINCT * WHERE { wd:'+Qid+' rdfs:label ?label . FILTER (langMatches( lang(?label), "EN" ) ) }') # the previous query as a literal string
        data=sparql.query().convert()
        results=data["results"]["bindings"]
        results=[res["label"]["value"] for res in results]
        return results

    except:
        return [ ]

def enwiki_title_to_wikidata_id(title: str) -> str:
    try:
        protocol = 'https'
        base_url = 'en.wikipedia.org/w/api.php'
        params = f'action=query&prop=pageprops&format=json&titles={title}'
        url = f'{protocol}://{base_url}?{params}'

        response = requests.get(url)
        json = response.json()
        for pages in json['query']['pages'].values():
            wikidata_id = pages['pageprops']['wikibase_item']
        return wikidata_id
    except:
        return None
Related