<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def build_ontologies(self, exclude_BNodes=False, return_string=False):
 """ Extract ontology instances info from the graph, then creates python objects for them. Note: often ontology info is nested in structures like this: [ a owl:Ontology ; vann:preferredNamespacePrefix "bsym" ; vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ] Hence there is some logic to deal with these edge cases. """

        out = []

        qres = self.sparqlHelper.getOntology()

        if qres:
            # NOTE: SPARQL returns a list of rdflib.query.ResultRow (~ tuples..)

            for candidate in qres:
                if isBlankNode(candidate[0]):
                    if exclude_BNodes:
                        continue
                    else:
                        checkDC_ID = [x for x in self.rdflib_graph.objects(
                            candidate[0], rdflib.namespace.DC.identifier)]
                        if checkDC_ID:
                            out += [Ontology(checkDC_ID[0], namespaces=self.namespaces), ]
                        else:
                            vannprop = rdflib.URIRef(
                                "http://purl.org/vocab/vann/preferredNamespaceUri")
                            vannpref = rdflib.URIRef(
                                "http://purl.org/vocab/vann/preferredNamespacePrefix")
                            checkDC_ID = [x for x in self.rdflib_graph.objects(
                                candidate[0], vannprop)]
                            if checkDC_ID:
                                checkDC_prefix = [
                                    x for x in self.rdflib_graph.objects(candidate[0], vannpref)]
                                if checkDC_prefix:
                                    out += [Ontology(checkDC_ID[0],
                                                     namespaces=self.namespaces,
                                                     prefPrefix=checkDC_prefix[0])]
                                else:
                                    out += [Ontology(checkDC_ID[0], namespaces=self.namespaces)]

                else:
                    out += [Ontology(candidate[0], namespaces=self.namespaces)]

        else:
            pass
            # printDebug("No owl:Ontologies found")

        # finally... add all annotations/triples
        self.all_ontologies = out
        for onto in self.all_ontologies:
            onto.triples = self.sparqlHelper.entityTriples(onto.uri)
            onto._buildGraph()