Python rdflib 模块,namespace() 实例源码

我们从Python开源项目中,提取了以下20个代码示例,用于说明如何使用rdflib.namespace()

项目:genepio    作者:GenEpiO    | 项目源码 | 文件源码
def __init__(self, namespace={}, prefixes='', newqueries={}):

        self.graph = rdflib.Graph()

        self.namespace.update(namespace)
        self.prefixes += prefixes
        # run all given "SELECT" queries through prepareQuery function.
        for (id, query) in newqueries.iteritems():
            leader = query.strip()[0:6]
            if leader == 'SELECT': # prepareQuery only works on SELECT ...
                self.queries[id] = rdflib.plugins.sparql.prepareQuery(query, initNs = self.namespace)
                print "Adding SELECT query"

            elif leader == 'DELETE' or leader == 'INSERT':
                self.queries[id] = query
                print "Adding DEL/INS query"
        #self.queries.update(queries)
        #print "Done query prep."
项目:genepio    作者:GenEpiO    | 项目源码 | 文件源码
def do_query_update(self, query_name, initBinds = {}):
        """
        Given a sparql 1.1 update query, perform it. 
        """

        query = self.queries[query_name]

        try:
            # Doesn't work?! fails silently.
            result = self.graph.update(self.prefixes + query, initBindings=initBinds, initNs=self.namespace)
            #result = processUpdate(self.graph, self.prefixes + query, initBindings=initBinds, initNs=self.namespace)
        except Exception as e:
            print ("\nSparql query [%s] parsing problem: %s \n" % (query_name, str(e) ))
            return None

        return result
项目:genepio    作者:GenEpiO    | 项目源码 | 文件源码
def doQueryUpdate(self, query_name, initBinds = {}):
        """
        Given a sparql 1.1 update query, perform it. 
        """

        query = self.queries[query_name]

        try:
            # Doesn't work?! fails silently.
            #result = self.graph.update(self.prefixes + query, initBindings=initBinds, initNs=self.namespace)
            result = processUpdate(self.graph, self.prefixes + query, initBindings=initBinds, initNs=self.namespace)
        except Exception as e:
            print ("\nSparql query [%s] parsing problem: %s \n" % (query_name, str(e) ))
            return None

        return result
项目:genepio    作者:GenEpiO    | 项目源码 | 文件源码
def doQueryUpdate(self, query_name, initBinds = {}):
        """
        Given a sparql 1.1 update query, perform it. 
        """

        query = self.queries[query_name]

        try:
            # Doesn't work?! fails silently.
            #result = self.graph.update(self.prefixes + query, initBindings=initBinds, initNs=self.namespace)
            result = processUpdate(self.graph, self.prefixes + query, initBindings=initBinds, initNs=self.namespace)
        except Exception as e:
            print ("\nSparql query [%s] parsing problem: %s \n" % (query_name, str(e) ))
            return None

        return result
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def __neg__(self):
        """
        >>> (- Literal(1))
        rdflib.term.Literal(%(u)s'-1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))
        >>> (- Literal(10.5))
        rdflib.term.Literal(%(u)s'-10.5', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#double'))
        >>> from rdflib.namespace import XSD
        >>> (- Literal("1", datatype=XSD.integer))
        rdflib.term.Literal(%(u)s'-1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))

        >>> (- Literal("1"))
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: Not a number; rdflib.term.Literal(%(u)s'1')
        >>>
        """

        if isinstance(self.value, (int, long, float)):
            return Literal(self.value.__neg__())
        else:
            raise TypeError("Not a number; %s" % repr(self))
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def __pos__(self):
        """
        >>> (+ Literal(1))
        rdflib.term.Literal(%(u)s'1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))
        >>> (+ Literal(-1))
        rdflib.term.Literal(%(u)s'-1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))
        >>> from rdflib.namespace import XSD
        >>> (+ Literal("-1", datatype=XSD.integer))
        rdflib.term.Literal(%(u)s'-1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))

        >>> (+ Literal("1"))
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: Not a number; rdflib.term.Literal(%(u)s'1')
        """
        if isinstance(self.value, (int, long, float)):
            return Literal(self.value.__pos__())
        else:
            raise TypeError("Not a number; %s" % repr(self))
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def __abs__(self):
        """
        >>> abs(Literal(-1))
        rdflib.term.Literal(%(u)s'1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))

        >>> from rdflib.namespace import XSD
        >>> abs( Literal("-1", datatype=XSD.integer))
        rdflib.term.Literal(%(u)s'1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))

        >>> abs(Literal("1"))
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: Not a number; rdflib.term.Literal(%(u)s'1')
        """
        if isinstance(self.value, (int, long, float)):
            return Literal(self.value.__abs__())
        else:
            raise TypeError("Not a number; %s" % repr(self))
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def __invert__(self):
        """
        >>> ~(Literal(-1))
        rdflib.term.Literal(%(u)s'0', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))

        >>> from rdflib.namespace import XSD
        >>> ~( Literal("-1", datatype=XSD.integer))
        rdflib.term.Literal(%(u)s'0', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))

        Not working:

        >>> ~(Literal("1"))
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: Not a number; rdflib.term.Literal(%(u)s'1')
        """
        if isinstance(self.value, (int, long, float)):
            return Literal(self.value.__invert__())
        else:
            raise TypeError("Not a number; %s" % repr(self))
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def __neg__(self):
        """
        >>> (- Literal(1))
        rdflib.term.Literal(%(u)s'-1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))
        >>> (- Literal(10.5))
        rdflib.term.Literal(%(u)s'-10.5', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#double'))
        >>> from rdflib.namespace import XSD
        >>> (- Literal("1", datatype=XSD.integer))
        rdflib.term.Literal(%(u)s'-1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))

        >>> (- Literal("1"))
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: Not a number; rdflib.term.Literal(%(u)s'1')
        >>>
        """

        if isinstance(self.value, (int, long, float)):
            return Literal(self.value.__neg__())
        else:
            raise TypeError("Not a number; %s" % repr(self))
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def __pos__(self):
        """
        >>> (+ Literal(1))
        rdflib.term.Literal(%(u)s'1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))
        >>> (+ Literal(-1))
        rdflib.term.Literal(%(u)s'-1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))
        >>> from rdflib.namespace import XSD
        >>> (+ Literal("-1", datatype=XSD.integer))
        rdflib.term.Literal(%(u)s'-1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))

        >>> (+ Literal("1"))
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: Not a number; rdflib.term.Literal(%(u)s'1')
        """
        if isinstance(self.value, (int, long, float)):
            return Literal(self.value.__pos__())
        else:
            raise TypeError("Not a number; %s" % repr(self))
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def __abs__(self):
        """
        >>> abs(Literal(-1))
        rdflib.term.Literal(%(u)s'1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))

        >>> from rdflib.namespace import XSD
        >>> abs( Literal("-1", datatype=XSD.integer))
        rdflib.term.Literal(%(u)s'1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))

        >>> abs(Literal("1"))
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: Not a number; rdflib.term.Literal(%(u)s'1')
        """
        if isinstance(self.value, (int, long, float)):
            return Literal(self.value.__abs__())
        else:
            raise TypeError("Not a number; %s" % repr(self))
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def __invert__(self):
        """
        >>> ~(Literal(-1))
        rdflib.term.Literal(%(u)s'0', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))

        >>> from rdflib.namespace import XSD
        >>> ~( Literal("-1", datatype=XSD.integer))
        rdflib.term.Literal(%(u)s'0', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))

        Not working:

        >>> ~(Literal("1"))
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: Not a number; rdflib.term.Literal(%(u)s'1')
        """
        if isinstance(self.value, (int, long, float)):
            return Literal(self.value.__invert__())
        else:
            raise TypeError("Not a number; %s" % repr(self))
项目:genepio    作者:GenEpiO    | 项目源码 | 文件源码
def get_ontology_imports(self, ontology_file_path='./imports/'):
        """
        Detects all the import files in a loaded OWL ontology graph and adds them to the graph.
        Currently assumes imports are sitting in a folder called "imports" in parent folder of this script. 
        """
        query = rdflib.plugins.sparql.prepareQuery("""
            SELECT distinct ?import_file
            WHERE {?s owl:imports ?import_file . }
            ORDER BY (?import_file)
        """, initNs = self.namespace)

        imports = self.graph.query(query, initNs = self.namespace)

        print("It has %s import files ..." % len(imports))

        for result_row in imports: # a rdflib.query.ResultRow
            file = result_row.import_file.rsplit('/',1)[1]
            file_path = ontology_file_path + '/' + file
            try:
                if os.path.isfile( file_path):
                    self.graph.parse(file_path) 
                else:
                    print ('WARNING:' + file_path + " could not be loaded!  Does its ontology include purl have a corresponding local file? \n")

            except rdflib.exceptions.ParserError as e:
                print (file_path + " needs to be in RDF OWL format!")
项目:dati-ckan-docker    作者:italia    | 项目源码 | 文件源码
def graph_from_catalog(self, catalog_dict, catalog_ref):

        g = self.g

        for prefix, namespace in namespaces.iteritems():
            g.bind(prefix, namespace)

        g.add((catalog_ref, RDF.type, DCAT.Catalog))

        # Basic fields
        items = [
            ('title', DCT.title, config.get('ckan.site_title'), Literal),
            ('description', DCT.description, config.get('ckan.site_description'), Literal),
            ('homepage', FOAF.homepage, config.get('ckan.site_url'), URIRef),
            ('language', DCT.language, config.get('ckan.locale_default', 'en'), Literal),
        ]
        for item in items:
            key, predicate, fallback, _type = item
            if catalog_dict:
                value = catalog_dict.get(key, fallback)
            else:
                value = fallback
            if value:
                g.add((catalog_ref, predicate, _type(value)))

        # Dates
        modified = self._last_catalog_modification()
        if modified:
            self._add_date_triple(catalog_ref, DCT.modified, modified)
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def __le__(self, other):
        """
        >>> from rdflib.namespace import XSD
        >>> Literal('2007-01-01T10:00:00', datatype=XSD.dateTime
        ...     ) <= Literal('2007-01-01T10:00:00', datatype=XSD.dateTime)
        True
        """
        r = self.__lt__(other)
        if r:
            return True
        try:
            return self.eq(other)
        except TypeError:
            return NotImplemented
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def __le__(self, other):
        """
        >>> from rdflib.namespace import XSD
        >>> Literal('2007-01-01T10:00:00', datatype=XSD.dateTime
        ...     ) <= Literal('2007-01-01T10:00:00', datatype=XSD.dateTime)
        True
        """
        r = self.__lt__(other)
        if r:
            return True
        try:
            return self.eq(other)
        except TypeError:
            return NotImplemented
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def n3(self, namespace_manager = None):
        r'''
        Returns a representation in the N3 format.

        Examples::

            >>> Literal("foo").n3()
            %(u)s'"foo"'

        Strings with newlines or triple-quotes::

            >>> Literal("foo\nbar").n3()
            %(u)s'"""foo\nbar"""'

            >>> Literal("''\'").n3()
            %(u)s'"\'\'\'"'

            >>> Literal('"""').n3()
            %(u)s'"\\"\\"\\""'

        Language::

            >>> Literal("hello", lang="en").n3()
            %(u)s'"hello"@en'

        Datatypes::

            >>> Literal(1).n3()
            %(u)s'"1"^^<http://www.w3.org/2001/XMLSchema#integer>'

            >>> Literal(1.0).n3()
            %(u)s'"1.0"^^<http://www.w3.org/2001/XMLSchema#double>'

            >>> Literal(True).n3()
            %(u)s'"true"^^<http://www.w3.org/2001/XMLSchema#boolean>'

        Datatype and language isn't allowed (datatype takes precedence)::

            >>> Literal(1, lang="en").n3()
            %(u)s'"1"^^<http://www.w3.org/2001/XMLSchema#integer>'

        Custom datatype::

            >>> footype = URIRef("http://example.org/ns#foo")
            >>> Literal("1", datatype=footype).n3()
            %(u)s'"1"^^<http://example.org/ns#foo>'

        Passing a namespace-manager will use it to abbreviate datatype URIs:

            >>> from rdflib import Graph
            >>> Literal(1).n3(Graph().namespace_manager)
            %(u)s'"1"^^xsd:integer'
        '''
        if namespace_manager:
            return self._literal_n3(qname_callback =
                                    namespace_manager.normalizeUri)
        else:
            return self._literal_n3()
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def make_option_parser():
    parser_names = _get_plugin_names(Parser)
    serializer_names = _get_plugin_names(Serializer)
    kw_example = "FORMAT:(+)KW1,-KW2,KW3=VALUE"

    oparser = OptionParser(
        "%prog [-h] [-i INPUT_FORMAT] [-o OUTPUT_FORMAT] " +
        "[--ns=PFX=NS ...] [-] [FILE ...]",
        description=__doc__.strip() + (
        " Reads file system paths, URLs or from stdin if '-' is given."
        " The result is serialized to stdout."),
        version="%prog " + "(using rdflib %s)" % rdflib.__version__)

    oparser.add_option(
        '-i', '--input-format',
        type=str,  # default=DEFAULT_INPUT_FORMAT,
        help="Format of the input document(s)."
        " Available input formats are: %s." % parser_names +
        " If no format is given, it will be " +
        "guessed from the file name extension." +
        " Keywords to parser can be given after format like: %s." % kw_example,
        metavar="INPUT_FORMAT")

    oparser.add_option(
        '-o', '--output-format',
        type=str, default=DEFAULT_OUTPUT_FORMAT,
        help="Format of the graph serialization."
        " Available output formats are: %s."
        % serializer_names +
        " Default format is: '%default'." +
        " Keywords to serializer can be given after format like: %s." %
        kw_example,
        metavar="OUTPUT_FORMAT")

    oparser.add_option(
        '--ns',
        action="append", type=str,
        help="Register a namespace binding (QName prefix to a base URI). "
        "This can be used more than once.",
        metavar="PREFIX=NAMESPACE")

    oparser.add_option(
        '--no-guess', dest='guess',
        action='store_false', default=True,
        help="Don't guess format based on file suffix.")

    oparser.add_option(
        '--no-out',
        action='store_true', default=False,
        help="Don't output the resulting graph " +
             "(useful for checking validity of input).")

    oparser.add_option(
        '-w', '--warn',
        action='store_true', default=False,
        help="Output warnings to stderr (by default only critical errors).")

    return oparser
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def n3(self, namespace_manager = None):
        r'''
        Returns a representation in the N3 format.

        Examples::

            >>> Literal("foo").n3()
            %(u)s'"foo"'

        Strings with newlines or triple-quotes::

            >>> Literal("foo\nbar").n3()
            %(u)s'"""foo\nbar"""'

            >>> Literal("''\'").n3()
            %(u)s'"\'\'\'"'

            >>> Literal('"""').n3()
            %(u)s'"\\"\\"\\""'

        Language::

            >>> Literal("hello", lang="en").n3()
            %(u)s'"hello"@en'

        Datatypes::

            >>> Literal(1).n3()
            %(u)s'"1"^^<http://www.w3.org/2001/XMLSchema#integer>'

            >>> Literal(1.0).n3()
            %(u)s'"1.0"^^<http://www.w3.org/2001/XMLSchema#double>'

            >>> Literal(True).n3()
            %(u)s'"true"^^<http://www.w3.org/2001/XMLSchema#boolean>'

        Datatype and language isn't allowed (datatype takes precedence)::

            >>> Literal(1, lang="en").n3()
            %(u)s'"1"^^<http://www.w3.org/2001/XMLSchema#integer>'

        Custom datatype::

            >>> footype = URIRef("http://example.org/ns#foo")
            >>> Literal("1", datatype=footype).n3()
            %(u)s'"1"^^<http://example.org/ns#foo>'

        Passing a namespace-manager will use it to abbreviate datatype URIs:

            >>> from rdflib import Graph
            >>> Literal(1).n3(Graph().namespace_manager)
            %(u)s'"1"^^xsd:integer'
        '''
        if namespace_manager:
            return self._literal_n3(qname_callback =
                                    namespace_manager.normalizeUri)
        else:
            return self._literal_n3()
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def make_option_parser():
    parser_names = _get_plugin_names(Parser)
    serializer_names = _get_plugin_names(Serializer)
    kw_example = "FORMAT:(+)KW1,-KW2,KW3=VALUE"

    oparser = OptionParser(
        "%prog [-h] [-i INPUT_FORMAT] [-o OUTPUT_FORMAT] " +
        "[--ns=PFX=NS ...] [-] [FILE ...]",
        description=__doc__.strip() + (
        " Reads file system paths, URLs or from stdin if '-' is given."
        " The result is serialized to stdout."),
        version="%prog " + "(using rdflib %s)" % rdflib.__version__)

    oparser.add_option(
        '-i', '--input-format',
        type=str,  # default=DEFAULT_INPUT_FORMAT,
        help="Format of the input document(s)."
        " Available input formats are: %s." % parser_names +
        " If no format is given, it will be " +
        "guessed from the file name extension." +
        " Keywords to parser can be given after format like: %s." % kw_example,
        metavar="INPUT_FORMAT")

    oparser.add_option(
        '-o', '--output-format',
        type=str, default=DEFAULT_OUTPUT_FORMAT,
        help="Format of the graph serialization."
        " Available output formats are: %s."
        % serializer_names +
        " Default format is: '%default'." +
        " Keywords to serializer can be given after format like: %s." %
        kw_example,
        metavar="OUTPUT_FORMAT")

    oparser.add_option(
        '--ns',
        action="append", type=str,
        help="Register a namespace binding (QName prefix to a base URI). "
        "This can be used more than once.",
        metavar="PREFIX=NAMESPACE")

    oparser.add_option(
        '--no-guess', dest='guess',
        action='store_false', default=True,
        help="Don't guess format based on file suffix.")

    oparser.add_option(
        '--no-out',
        action='store_true', default=False,
        help="Don't output the resulting graph " +
             "(useful for checking validity of input).")

    oparser.add_option(
        '-w', '--warn',
        action='store_true', default=False,
        help="Output warnings to stderr (by default only critical errors).")

    return oparser