Python rdflib 模块,RDF 实例源码

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

项目:open-semantic-search-apps    作者:opensemanticsearch    | 项目源码 | 文件源码
def edit_annotation(request):

    uri = request.GET['uri']

    annotations = Annotation.objects.filter(uri=uri)

    if annotations:

        # get first primary key of annotation with given uri
        pk = annotations[0].pk
        annotation = Annotation.objects.get(pk=pk)

        #todo: warning message if more (if racing condition on creation)

        # redirect to edit this annotation
        return HttpResponseRedirect( reverse('annotate:update', args=[pk])) # Redirect after POST

    else:
        # no annotation for that uri, so redirect to create view
        return HttpResponseRedirect( "{}?uri={}".format( reverse('annotate:create'), urllib.parse.quote_plus( uri ) ) ) # Redirect after POST



# serialize tags for uri to RDF graph
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def generate_RDF_collection( graph, vals ) :
    """
    Generate an RDF List from vals, returns the head of the list
    @param graph: RDF graph
    @type graph: RDFLib Graph
    @param vals: array of RDF Resources
    @return: head of the List (an RDF Resource)
    """
    # generate an RDF List, returns the head
    # list has all the elements in RDF format already
    heads = [ BNode() for r in vals ] + [ ns_rdf["nil"] ]
    for i in range(0, len(vals)) :
        graph.add( (heads[i], ns_rdf["first"], vals[i]) )
        graph.add( (heads[i], ns_rdf["rest"],  heads[i+1]) )
    return heads[0]

#################################################################################
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def generate_RDF_collection( graph, vals ) :
    """
    Generate an RDF List from vals, returns the head of the list
    @param graph: RDF graph
    @type graph: RDFLib Graph
    @param vals: array of RDF Resources
    @return: head of the List (an RDF Resource)
    """
    # generate an RDF List, returns the head
    # list has all the elements in RDF format already
    heads = [ BNode() for r in vals ] + [ ns_rdf["nil"] ]
    for i in range(0, len(vals)) :
        graph.add( (heads[i], ns_rdf["first"], vals[i]) )
        graph.add( (heads[i], ns_rdf["rest"],  heads[i+1]) )
    return heads[0]

#################################################################################
项目:programming-the-semantic-web    作者:utecht    | 项目源码 | 文件源码
def get_in_theaters():
    #stream=urlopen('http://www.videodetective.com/api/intheaters.aspx?DeveloperId={KEY}')
    #stream=urlopen('http://semprog.com/data/intheaters.xml')
    stream=file('intheaters.xml')

    root=parse(stream)
    stream.close()

    movies=[]

    for item in root.getElementsByTagName('item'):
        movie={}

        # Get the ID, title, and director
        movie['id']=getdata(item,'PublishedId')
        movie['title']=getdata(item,'Title')
        movie['director']={'id':getdata(item,'DirectorID'),'name':getdata(item,'Director')}

        # Actor tags are numbered: Actor1, Actor2, etc.
        movie['actors']=[]    
        for i in range(1,6):
            actor=getdata(item,'Actor%d' % i)
            actorid=getdata(item,'ActorId%d' % i)

            if actor!=None and actorid!=None:
                movie['actors'].append({'name':actor,'id':actorid})

        movies.append(movie)

    return movies

# Generate an RDF Graph from the Movie Data
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def get_list_value(self,prop) :
        """
        Return the list of values in the list structure for a specific property
        @return: list of RDF nodes
        """
        return self.list_mapping.mapping[prop]
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def handle_prototypes(graph) :
    to_remove = set()
    for (x,ref,PR) in graph.triples((None,pref,None)) :
        if (PR,ns_rdf["type"],Prototype) in graph :
            to_remove.add((PR,ns_rdf["type"],Prototype))
            to_remove.add((x,ref,PR))
            # there is a reference to a prototype here
            for (PR,p,y) in graph.triples((PR,None,None)) :
                if not ( p == ns_rdf["type"] and y == Prototype ) :
                    graph.add((x,p,y))
                    to_remove.add((PR,p,y))
    for t in to_remove : graph.remove(t)
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def add_http_context(self, subj, http_code) :
        """
        Add an additional HTTP context to a message with subject in C{subj}, using the U{<http://www.w3.org/2006/http#>}
        vocabulary. Typically used to extend an error structure, as created by L{add_triples}.

        @param subj: an RDFLib resource, typically a blank node
        @param http_code: HTTP status code
        """
        bnode = BNode()
        self.graph.add((subj, ns_rdfa["context"], bnode))
        self.graph.add((bnode, ns_rdf["type"], ns_ht["Response"]))
        self.graph.add((bnode, ns_ht["responseCode"], URIRef("http://www.w3.org/2006/http#%s" % http_code)))
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def rdf_from_sources(self, names, outputFormat = "turtle", rdfOutput = False) :
        """
        Extract and RDF graph from a list of RDFa sources and serialize them in one graph. The sources are parsed, the RDF
        extracted, and serialization is done in the specified format.
        @param names: list of sources, each can be a URI, a file name, or a file-like object
        @keyword outputFormat: serialization format. Can be one of "turtle", "n3", "xml", "pretty-xml", "nt". "xml", "pretty-xml", "json" or "json-ld". "turtle" and "n3", "xml" and "pretty-xml", and "json" and "json-ld" are synonyms, respectively. Note that the JSON-LD serialization works with RDFLib 3.* only.
        @keyword rdfOutput: controls what happens in case an exception is raised. If the value is False, the caller is responsible handling it; otherwise a graph is returned with an error message included in the processor graph
        @type rdfOutput: boolean
        @return: a serialized RDF Graph
        @rtype: string
        """
        # This is better because it gives access to the various, non-standard serializations
        # If it does not work because the extra are not installed, fall back to the standard
        # rdlib distribution...
        try :
            from pyRdfaExtras import MyGraph
            graph = MyGraph()
        except :
            graph = Graph()

        # graph.bind("xsd", Namespace('http://www.w3.org/2001/XMLSchema#'))
        # the value of rdfOutput determines the reaction on exceptions...
        for name in names :
            self.graph_from_source(name, graph, rdfOutput)
        retval = graph.serialize(format=outputFormat)
        return retval
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def _generate_error_graph(self, pgraph, full_msg, uri = None) :
        """
        Generate an error message into the graph. This method is usually used reacting on exceptions.

        Later versions of pyMicrodata may have more detailed error conditions on which it wishes to react. At the moment, this
        is fairly crude...
        """
        if pgraph == None :
            retval = Graph()
        else :
            retval = pgraph

        pgraph.bind( "dc","http://purl.org/dc/terms/" )
        pgraph.bind( "xsd",'http://www.w3.org/2001/XMLSchema#' )
        pgraph.bind( "ht",'http://www.w3.org/2006/http#' )
        pgraph.bind( "pyMicrodata",'http://www.w3.org/2012/pyMicrodata/vocab#' )

        bnode = BNode()
        retval.add((bnode, ns_rdf["type"], ns_micro["Error"]))
        retval.add((bnode, ns_dc["description"], Literal(full_msg)))
        retval.add((bnode, ns_dc["date"], Literal(datetime.datetime.utcnow().isoformat(),datatype=ns_xsd["dateTime"])))

        if uri != None :
            htbnode = BNode()
            retval.add( (bnode, ns_micro["context"],htbnode) )
            retval.add( (htbnode, ns_rdf["type"], ns_ht["Request"]) )
            retval.add( (htbnode, ns_ht["requestURI"], Literal(uri)) )

        if self.http_status != None and self.http_status != 200:
            htbnode = BNode()
            retval.add( (bnode, ns_micro["context"],htbnode) )
            retval.add( (htbnode, ns_rdf["type"], ns_ht["Response"]) )
            retval.add( (htbnode, ns_ht["responseCode"], URIRef("http://www.w3.org/2006/http#%s" % self.http_status)) )

        return retval
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def get_list_value(self,prop) :
        """
        Return the list of values in the list structure for a specific property
        @return: list of RDF nodes
        """
        return self.list_mapping.mapping[prop]
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def handle_prototypes(graph) :
    to_remove = set()
    for (x,ref,PR) in graph.triples((None,pref,None)) :
        if (PR,ns_rdf["type"],Prototype) in graph :
            to_remove.add((PR,ns_rdf["type"],Prototype))
            to_remove.add((x,ref,PR))
            # there is a reference to a prototype here
            for (PR,p,y) in graph.triples((PR,None,None)) :
                if not ( p == ns_rdf["type"] and y == Prototype ) :
                    graph.add((x,p,y))
                    to_remove.add((PR,p,y))
    for t in to_remove : graph.remove(t)
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def add_http_context(self, subj, http_code) :
        """
        Add an additional HTTP context to a message with subject in C{subj}, using the U{<http://www.w3.org/2006/http#>}
        vocabulary. Typically used to extend an error structure, as created by L{add_triples}.

        @param subj: an RDFLib resource, typically a blank node
        @param http_code: HTTP status code
        """
        bnode = BNode()
        self.graph.add((subj, ns_rdfa["context"], bnode))
        self.graph.add((bnode, ns_rdf["type"], ns_ht["Response"]))
        self.graph.add((bnode, ns_ht["responseCode"], URIRef("http://www.w3.org/2006/http#%s" % http_code)))
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def rdf_from_sources(self, names, outputFormat = "turtle", rdfOutput = False) :
        """
        Extract and RDF graph from a list of RDFa sources and serialize them in one graph. The sources are parsed, the RDF
        extracted, and serialization is done in the specified format.
        @param names: list of sources, each can be a URI, a file name, or a file-like object
        @keyword outputFormat: serialization format. Can be one of "turtle", "n3", "xml", "pretty-xml", "nt". "xml", "pretty-xml", "json" or "json-ld". "turtle" and "n3", "xml" and "pretty-xml", and "json" and "json-ld" are synonyms, respectively. Note that the JSON-LD serialization works with RDFLib 3.* only.
        @keyword rdfOutput: controls what happens in case an exception is raised. If the value is False, the caller is responsible handling it; otherwise a graph is returned with an error message included in the processor graph
        @type rdfOutput: boolean
        @return: a serialized RDF Graph
        @rtype: string
        """
        # This is better because it gives access to the various, non-standard serializations
        # If it does not work because the extra are not installed, fall back to the standard
        # rdlib distribution...
        try :
            from pyRdfaExtras import MyGraph
            graph = MyGraph()
        except :
            graph = Graph()

        # graph.bind("xsd", Namespace('http://www.w3.org/2001/XMLSchema#'))
        # the value of rdfOutput determines the reaction on exceptions...
        for name in names :
            self.graph_from_source(name, graph, rdfOutput)
        retval = graph.serialize(format=outputFormat)
        return retval
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def _generate_error_graph(self, pgraph, full_msg, uri = None) :
        """
        Generate an error message into the graph. This method is usually used reacting on exceptions.

        Later versions of pyMicrodata may have more detailed error conditions on which it wishes to react. At the moment, this
        is fairly crude...
        """
        if pgraph == None :
            retval = Graph()
        else :
            retval = pgraph

        pgraph.bind( "dc","http://purl.org/dc/terms/" )
        pgraph.bind( "xsd",'http://www.w3.org/2001/XMLSchema#' )
        pgraph.bind( "ht",'http://www.w3.org/2006/http#' )
        pgraph.bind( "pyMicrodata",'http://www.w3.org/2012/pyMicrodata/vocab#' )

        bnode = BNode()
        retval.add((bnode, ns_rdf["type"], ns_micro["Error"]))
        retval.add((bnode, ns_dc["description"], Literal(full_msg)))
        retval.add((bnode, ns_dc["date"], Literal(datetime.datetime.utcnow().isoformat(),datatype=ns_xsd["dateTime"])))

        if uri != None :
            htbnode = BNode()
            retval.add( (bnode, ns_micro["context"],htbnode) )
            retval.add( (htbnode, ns_rdf["type"], ns_ht["Request"]) )
            retval.add( (htbnode, ns_ht["requestURI"], Literal(uri)) )

        if self.http_status != None and self.http_status != 200:
            htbnode = BNode()
            retval.add( (bnode, ns_micro["context"],htbnode) )
            retval.add( (htbnode, ns_rdf["type"], ns_ht["Response"]) )
            retval.add( (htbnode, ns_ht["responseCode"], URIRef("http://www.w3.org/2006/http#%s" % self.http_status)) )

        return retval
项目:Meiji    作者:GiovanniBalestrieri    | 项目源码 | 文件源码
def add_triples(self, msg, top_class, info_class, context, node) :
        """
        Add an error structure to the processor graph: a bnode with a number of predicates. The structure
        follows U{the processor graph vocabulary<http://www.w3.org/2010/02/rdfa/wiki/Processor_Graph_Vocabulary>} as described
        on the RDFa WG Wiki page.

        @param msg: the core error message, added as an object to a dc:description
        @param top_class: Error, Warning, or Info; an explicit rdf:type added to the bnode
        @type top_class: URIRef
        @param info_class: An additional error class, added as an rdf:type to the bnode in case it is not None
        @type info_class: URIRef
        @param context: An additional information added, if not None, as an object with rdfa:context as a predicate
        @type context: either an URIRef or a URI String (an URIRef will be created in the second case)
        @param node: The node's element name that contains the error
        @type node: string
        @return: the bnode that serves as a subject for the errors. The caller may add additional information
        @rtype: BNode
        """
        # Lazy binding of relevant prefixes
        self.graph.bind("dcterms", ns_dc)
        self.graph.bind("pyrdfa",  ns_distill)
        self.graph.bind("rdf",     ns_rdf)
        self.graph.bind("rdfa",    ns_rdfa)
        self.graph.bind("ht",      ns_ht)
        self.graph.bind("xsd",     ns_xsd)
        # Python 3 foolproof way
        try :
            is_context_string = isinstance(context, basestring)
        except :
            is_context_string = isinstance(context, str)

        bnode = BNode()

        if node != None:
            try :
                full_msg = "[In element '%s'] %s" % (node.nodeName, msg)
            except :
                full_msg = "[In element '%s'] %s" % (node, msg)
        else :
            full_msg = msg

        self.graph.add((bnode, ns_rdf["type"], top_class))
        if info_class :
            self.graph.add((bnode, ns_rdf["type"], info_class))
        self.graph.add((bnode, ns_dc["description"], Literal(full_msg)))
        self.graph.add((bnode, ns_dc["date"], Literal(datetime.datetime.utcnow().isoformat(),datatype=ns_xsd["dateTime"])))
        if context and (isinstance(context,URIRef) or is_context_string):
            htbnode = BNode()
            self.graph.add( (bnode,   ns_rdfa["context"],htbnode) )
            self.graph.add( (htbnode, ns_rdf["type"], ns_ht["Request"]) )
            self.graph.add( (htbnode, ns_ht["requestURI"], Literal("%s" % context)) )
        return bnode
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def add_triples(self, msg, top_class, info_class, context, node) :
        """
        Add an error structure to the processor graph: a bnode with a number of predicates. The structure
        follows U{the processor graph vocabulary<http://www.w3.org/2010/02/rdfa/wiki/Processor_Graph_Vocabulary>} as described
        on the RDFa WG Wiki page.

        @param msg: the core error message, added as an object to a dc:description
        @param top_class: Error, Warning, or Info; an explicit rdf:type added to the bnode
        @type top_class: URIRef
        @param info_class: An additional error class, added as an rdf:type to the bnode in case it is not None
        @type info_class: URIRef
        @param context: An additional information added, if not None, as an object with rdfa:context as a predicate
        @type context: either an URIRef or a URI String (an URIRef will be created in the second case)
        @param node: The node's element name that contains the error
        @type node: string
        @return: the bnode that serves as a subject for the errors. The caller may add additional information
        @rtype: BNode
        """
        # Lazy binding of relevant prefixes
        self.graph.bind("dcterms", ns_dc)
        self.graph.bind("pyrdfa",  ns_distill)
        self.graph.bind("rdf",     ns_rdf)
        self.graph.bind("rdfa",    ns_rdfa)
        self.graph.bind("ht",      ns_ht)
        self.graph.bind("xsd",     ns_xsd)
        # Python 3 foolproof way
        try :
            is_context_string = isinstance(context, basestring)
        except :
            is_context_string = isinstance(context, str)

        bnode = BNode()

        if node != None:
            try :
                full_msg = "[In element '%s'] %s" % (node.nodeName, msg)
            except :
                full_msg = "[In element '%s'] %s" % (node, msg)
        else :
            full_msg = msg

        self.graph.add((bnode, ns_rdf["type"], top_class))
        if info_class :
            self.graph.add((bnode, ns_rdf["type"], info_class))
        self.graph.add((bnode, ns_dc["description"], Literal(full_msg)))
        self.graph.add((bnode, ns_dc["date"], Literal(datetime.datetime.utcnow().isoformat(),datatype=ns_xsd["dateTime"])))
        if context and (isinstance(context,URIRef) or is_context_string):
            htbnode = BNode()
            self.graph.add( (bnode,   ns_rdfa["context"],htbnode) )
            self.graph.add( (htbnode, ns_rdf["type"], ns_ht["Request"]) )
            self.graph.add( (htbnode, ns_ht["requestURI"], Literal("%s" % context)) )
        return bnode