Search code examples
pythonsparqlsemantic-webowlready

TypeError: expected string or bytes-like object in owlready library


I'm trying to query data with python in the owl file I created using the owlready library. But I get the following error. what would be the reason?

The code structure and received error are as follows.

from owlready2 import *
from urllib.request import urlopen
from rdflib.graph import Graph

onto = default_world.get_ontology("http://muratkilinc.com/ontologies/izmir.owl").load()

graph = default_world.as_rdflib_graph()
r = list(graph.query_owlready("""
    PREFIX uni:<http://muratkilinc.com/ontologies/izmir.owl>
    SELECT ?adi ?soyadi ?yas
    WHERE
    {
        ?turistler uni:yas ?yas.
        ?turistler uni:adi ?adi.
        ?turistler uni:soyadi ?soyadi.
        FILTER(?yas > 35).

    }"""))

results = default_world.as_rdflib_graph().query_owlready(r)
results = list(results)
print(results)

Error:

* Owlready2 * Warning: optimized Cython parser module 'owlready2_optimized' is not available, 
defaulting to slower Python implementation
Traceback (most recent call last):
  File "c:/Users/BAUM-PC/Desktop/izmir/sparql.py", line 21, in <module>
    results = list(results)
  File "C:\Users\BAUM-PC\AppData\Local\Programs\Python\Python37-32\lib\site- 
packages\owlready2\rdflib_store.py", line 261, in query_owlready
  File "C:\Users\BAUM-PC\AppData\Local\Programs\Python\Python37-32\lib\site- 
packages\rdflib\graph.py", line 1089, in query
    query_object, initBindings, initNs, **kwargs))
  File "C:\Users\BAUM-PC\AppData\Local\Programs\Python\Python37-32\lib\site- 
packages\rdflib\plugins\sparql\processor.py", line 74, in query
    parsetree = parseQuery(strOrQuery)
  File "C:\Users\BAUM-PC\AppData\Local\Programs\Python\Python37-32\lib\site- 
packages\rdflib\plugins\sparql\parser.py", line 1057, in parseQuery
    q = expandUnicodeEscapes(q)
  File "C:\Users\BAUM-PC\AppData\Local\Programs\Python\Python37-32\lib\site- 
packages\rdflib\plugins\sparql\parser.py", line 1048, in expandUnicodeEscapes
    return expandUnicodeEscapes_re.sub(expand, q)
TypeError: expected string or bytes-like object

Solution

  • You have to skip second query and error message will skip

    from owlready2 import *
    from rdflib.graph import Graph
    
    onto = default_world.get_ontology("http://muratkilinc.com/ontologies/izmir.owl").load()
    
    graph = default_world.as_rdflib_graph()
    
    r = list(graph.query_owlready("""
        PREFIX uni:<http://muratkilinc.com/ontologies/izmir.owl>
        SELECT ?adi ?soyadi ?yas
        WHERE
        {
            ?turistler uni:yas ?yas.
            ?turistler uni:adi ?adi.
            ?turistler uni:soyadi ?soyadi.
            FILTER(?yas > 35).
        }"""))
    
    print(list(r))
    

    It gives empty list - so it works without error message.

    Empty list is different problem - with query, not with code - so you should ask new question.