Using Python rdflib: how to include literals in sparql queries?

I can include URIs and variables in my queries, but I cannot include literals in my queries.

Here I have a code that successfully reads an RDF file, finds all RDF three times with skins: prefLabels, counts them, and then identifies a pair of keywords defined from a set of keywords:

import rdflib.plugins.sparql as sparql import rdflib import rdflib.graph as g graph = g.Graph() # Read the RDF file graph.parse( 'h:\......SKOSTaxonomy.rdf', format='xml') # Build and execute the query q = sparql.prepareQuery('SELECT ?s ?p ?o WHERE { ?s ?p ?o .}') p = rdflib.URIRef("http://www.w3.org/2004/02/skos/core#prefLabel") qres = graph.query(q, initBindings = {'p' : p}) print len(qres) # Look for keywords among the results keywords = set([u'Jackknifing', 'Technology-mapping', 'Something random']) for (subj, pred, obj) in qres: if obj.value in keywords: print obj.value 

As expected, this code prints:

 2299 Jackknifing Technology-mapping 

since Jackknifing and Technology-mapping are prefLabels in the file.

I really want to create and execute a Sparql query to find each keyword in turn. But this is where I peel off because I cannot put a string in the query. I tried this because Example:

 o = rdflib.Literal(u'Jackknifing') qres = graph.query(q, initBindings = {'p' : p, 'o' : o}) 

but qres is empty. I also tried to directly indicate a literal query, for example.

 q = sparql.prepareQuery('SELECT ?s ?p WHERE { ?s ?p "Technology-mapping" .}') qres = graph.query(q, initBindings = {'p' : p}) 

but also returns an empty result.

How are literals used in a query?

+4
source share
1 answer

If the literals in your data have data types or are strings with language tags, then plain text, that is, one without a data type or language tag entered in the query, will not match.

RDFLib docs on Literals show how to create literals using data types, but have no example of creating one with a language tag. However, the documents also have a source and signature for Literal __new__ :

 static __new__(lexical_or_value, lang=None, datatype=None, normalize=None) 

Since the letter in your data has a language tag ( 'en' ), you must create your literal as

 o = rdflib.Literal(u'Jackkifing',lang='en') 

so that the language tag is associated with the literal.

+2
source

Source: https://habr.com/ru/post/1486568/


All Articles