Search code examples
pythonowlontologyowlready

how to read information about ontology using owlready2


I am working in flask app and want to load ontology and print how many classes and how many individuals in this ontology

here is my code, it does not work

import flask
from owlready2 import *

app = flask.Flask(__name__)
app.config["DEBUG"] = True


@app.route('/', methods=['GET'])
def start():
    onto_path.append("pizza.owl")
    onto = get_ontology("pizza.owl")
    onto.load()
    print(onto.classes())
    print(list(onto.individuals()))

    html = ''
    html += '<h2>clases: ' + onto.classes() + '</br>'
    html += '<h3>individuals: ' + onto.individuals()    

    return html

    #return "<h1>Distant Reading Archive</h1><p>This site is a prototype API for distant reading of science fiction novels.</p>"

app.run()

Solution

  • The method classes() and individuals() returns a generator, so you should cast the generator into a list, and ask for the length of that object.

    n_classes = len(list(onto.classes()))
    n_individuals = len(list(onto.individuals()))
    

    After that, you should have the numbers on your variables and you can concatenate them with your HTML.