<jupyter_start><jupyter_text>**Querying with SPARQL**<jupyter_code>!pip install rdflib
from rdflib import Graph, URIRef
from rdflib.namespace import RDFS, SKOS
g = Graph()
g.parse('https://www.wikidata.org/wiki/Special:EntityData/Q2831.ttl')
len(g)
MJ = URIRef('http://www.wikidata.org/entity/Q2831')
for label in g.objects(MJ, SKOS.altLabel):
    print(label.value, label.language)
labels = g.preferredLabel(MJ, labelProperties=(SKOS.altLabel,))
for prop, label in labels:
    print(label.value, label.language)
# https://query.wikidata.org/#SELECT%20%3Flabel%0AWHERE%20%7B%0A%20%20wd%3AQ2831%20skos%3AaltLabel%20%3Flabel%20.%0A%7D
qres = g.query('''
    SELECT ?label
    WHERE {
        wd:Q2831 skos:altLabel ?label .
    }
''')
for label, *_ in qres:
    print(label.value, label.language)
qres = g.query('''
    SELECT DISTINCT ?label
    WHERE {
        wd:Q2831 rdfs:label | skos:prefLabel | skos:altLabel ?label .
        FILTER (lang(?label) = 'en')
    }
    ORDER BY ?label
''')
for label, *_ in qres:
    print(label)
qres = g.query('''
    SELECT ?label ?description
    WHERE {
        wd:Q2831 wdt:P166 ?award .
        ?award rdfs:label ?label .
        FILTER (lang(?label) = 'en')
        OPTIONAL {
            ?award schema:description ?description
            FILTER (lang(?description) = 'en')
        }
    }
''')

for label, description in qres:
    print(f'Award: {label:<55} Description: {description}')
%timeit -n 1000 list(g.objects(MJ, RDFS.label))
%timeit -n 1000 g.preferredLabel(MJ, labelProperties=(RDFS.label,))
%timeit -n 1000 g.query('SELECT ?label WHERE {wd:Q2831 rdfs:label ?label}')<jupyter_output>1.64 ms ± 51.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
{'fraction_non_alphanumeric': 0.15204678362573099, 'fraction_numerical': 0.046198830409356725, 'mean_word_length': 3.6243243243243244, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 4, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '73765', 'license': 'Apache-2.0', 'n_tokens_mistral': 718, 'n_tokens_neox': 643, 'n_words': 141, 'path': 'rdflib/05 SPARQL Query RDF data.ipynb', 'repo_name': 'jfmendozam/ontotoutra', 'size': '1710'}