pwin / owlready2

GNU Lesser General Public License v3.0
132 stars 22 forks source link

Adding a filter option when dumping or saving an ontology and its individuals #2

Closed versae closed 4 years ago

versae commented 4 years ago

Following this question in the mailing list, I've decided to implement the feature. I'm adding a new filter parameter option to the dump and save operations so only those individuals for which the filter function returns True are exported. With the new filter parameter, now the user can select what elements to export in a dump or save operation.

For example, a valid filter function could be a function that returns True for those individuals that are an instance of a specific class:

# Let's just keep the individuals of the classes we are interested in
def filter_func(graph, s, *args):
    classes = [graph.onto.Line, graph.onto.Word, graph.onto.Syllable]
    return (s >= 0 and any(isinstance(graph.onto.world._get_by_storid(s), cls)
                           for cls in classes))

Then, when saving, we just need to pass in the function as a parameter:

onto.save(file="file.xml", format="rdfxml", filter=filter_func)