1

How to obtain a given token type (uri, literal, ...) and location from a given sparql query using rdflib?

For instance, given the following query:

SELECT count(DISTINCT ?uri) as ?count
FROM graph WHERE {
   ?uri a ?type;
        graph:predicate_a ?c;
   FILTER(?c = xyz AND ?type != abc)
}

I'd like to implement a function get_token_position such that get_token_position('AND') would return 124 (location) and something like OperatorType.

Reading the documentation, I noticed the library implements utilities to build parsing trees for the queries, therefore I think that come out with this function would be easily done using that library.

Ps.: My motivation is that I need to convert "AND" and "OR" to "&&" and "||" whenever those strings are used as operations. Also, I think using the parsing tree would be a better solution than using a regex pattern.

Daniel
  • 127
  • 1
  • 9

1 Answers1

0

Can you further explain what you want to do? It seems like you are wanting to implement an extremely complex set of functions for a string replace??

s = """
SELECT count(DISTINCT ?uri) as ?count
FROM graph WHERE {
   ?uri a ?type;
        graph:predicate_a ?c;
   FILTER(?c = xyz AND ?type != abc)
}
"""

s = s.replace(" AND ", " && ")  # spaces around AND to avoid in-word matches

If you want to ensure that the replacement doesn't affect any values that might appear in the query through variable substitution, you could simple do this AND/&& etc replacement first and then the variable substitution second.

Nicholas Car
  • 1,164
  • 4
  • 7
  • If you do that, it will also replace "AND" by "&&" in uris containing the word AND. – Daniel Sep 06 '21 at 16:55
  • How about `s.replace(" AND ", " && ")`? It would be (almost) impossible for a URI to have AND with spaces around it in it. But also, where are the URIs in the query string?? There are no variable to placed in the query string so where would another AND come from? If you actually are using string variable substitution, (of _xyz_ & _abc_ perhaps) then I would simple replace ANDs before making that substitution. – Nicholas Car Sep 08 '21 at 00:46