当前位置: 首页>>代码示例>>Python>>正文


Python Graph.ConjunctiveGraph类代码示例

本文整理汇总了Python中rdflib.Graph.ConjunctiveGraph的典型用法代码示例。如果您正苦于以下问题:Python ConjunctiveGraph类的具体用法?Python ConjunctiveGraph怎么用?Python ConjunctiveGraph使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ConjunctiveGraph类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, path=None):
        self.__dict__ = self.__shared_state
        if (self.data == None):
            if (path == None):
                raise ValueError("djubby's configuration MUST be initialized a first time, read http://code.google.com/p/djubby/wiki/GettingStarted")
            else:
                self.path = os.path.abspath(path)
                logging.debug("Reading djubby's configuration from %s..." % self.path)
                if (not os.path.exists(self.path)):
                    raise ValueError("Not found a proper file at '%s' with a configuration for djubby. Please, provide a right path" % self.path)

                data = ConjunctiveGraph()
                data.bind("conf", ns.config) 
                try:
                    data.load(path, format='n3') 
                except Exception, e:
                    raise ValueError("Not found a proper N3 file at '%s' with a configuration for djubby. Please, provide a valid N3 file" % self.path)

                self.data = data
                try:
                    self.graph = self.get_value("sparqlDefaultGraph")
                    self.endpoint = self.get_value("sparqlEndpoint")
                except Exception, e:
                    raise ValueError("Not found the graph not the endpoint that it's supposed djubby have to query. Please, provide a right donfiguration")

                logging.info("Using <%s> as default graph to query the endpoint <%s>" % (self.graph, self.endpoint))
                self.__class__.__dict__['_Configuration__shared_state']["data"] = data #FIXME
开发者ID:kiivihal,项目名称:djubby,代码行数:27,代码来源:configuration.py

示例2: getGraph

def getGraph():
    """
    get the main graph, including data from trains.n3 on disk
    """
    graph = ConjunctiveGraph()
    graph.parse("trains.n3", format="n3", publicID=TT['disk#context'])
    return graph
开发者ID:drewp,项目名称:traintimes,代码行数:7,代码来源:localrdf.py

示例3: readGraphs

def readGraphs():
    g = ConjunctiveGraph()
    # this file should only be reread when it changes
    g.parse("../config.n3", format="n3")
    dl = []
    startTime = time.time()
    for uri in [
        "http://bang:9055/graph",
        "http://bang:9069/graph",
        "http://bang:9070/graph",
        "http://bang:9072/bang-9002/processStatus",
        "http://bang:9072/bang/processStatus",
        "http://bang:9072/dash/processStatus",
        "http://bang:9072/slash-11000/processStatus",
        "http://bang:9072/slash/processStatus",
        "http://bang:9072/star/processStatus",
        "http://bang:9075/graph",
        ]:
        # this ought to not reparse the ones that are 304 not modified
        d = getPage(uri)
        def done(trig, uri):
            g.addN(parseTrig(trig))
            print "%s done in %.02fms" % (uri, 1000 * (time.time() - startTime))
        d.addCallback(done, uri)
        dl.append(d)
    return defer.DeferredList(dl).addCallback(lambda result: g)
开发者ID:drewp,项目名称:magma,代码行数:26,代码来源:sensorstate.py

示例4: parse

 def parse(self, result):
     """
     Parse query result
     
     @param result: text result
     @return: rdf graph
     """        
     graph = ConjunctiveGraph()
     graph.parse(StringInputSource(result))
     return graph
开发者ID:BackupTheBerlios,项目名称:swaml-svn,代码行数:10,代码来源:sparlclient.py

示例5: testDefaultGraph

def testDefaultGraph():
    memStore = plugin.get('IOMemory',Store)()
    graph1 = Graph(memStore,URIRef("graph1"))
    graph2 = Graph(memStore,URIRef("graph2"))
    graph3 = Graph(memStore,URIRef("graph3"))
    
    for n3Str,graph in [(testGraph1N3,graph1),
                        (testGraph2N3,graph2),
                        (testGraph3N3,graph3)]:
        graph.parse(StringIO(n3Str),format='n3')
    G = ConjunctiveGraph(memStore)
    #test that CG includes triples from all 3
    assert G.query(sparqlQ3),"CG as default graph should *all* triples"
    assert not graph2.query(sparqlQ3),"Graph as default graph should *not* include triples from other graphs"
开发者ID:AuroraSkywalker,项目名称:watchdog,代码行数:14,代码来源:aggregate_graphs.py

示例6: testQueryingMore

 def testQueryingMore(self):
     for result in self.results:
         uri = result[0]
         g = ConjunctiveGraph()
         g.parse(uri)
         query = Parse("""
                             SELECT ?person
                             WHERE {
                                      <%s> foaf:primaryTopic ?person .
                                      ?person rdf:type foaf:Person . 
                                   }
                       """ % uri )
         queryResults = g.query(query, initNs=NSbindings).serialize('python')
         if (len(queryResults)>0):
             self.assertEquals(str(queryResults[0]), "http://www.wikier.org/foaf#wikier")
开发者ID:BackupTheBerlios,项目名称:swaml-svn,代码行数:15,代码来源:sindice.py

示例7: TestSPARQLToldBNodes

class TestSPARQLToldBNodes(unittest.TestCase):
    def setUp(self):
        NS = u"http://example.org/"
        self.graph = ConjunctiveGraph()
        self.graph.parse(StringInputSource("""
           @prefix    : <http://example.org/> .
           @prefix rdf: <%s> .
           @prefix rdfs: <%s> .
           [ :prop :val ].
           [ a rdfs:Class ]."""%(RDF.RDFNS,RDFS.RDFSNS)), format="n3")
    def testToldBNode(self):
        for s,p,o in self.graph.triples((None,RDF.type,None)):
            pass
        query = """SELECT ?obj WHERE { %s ?prop ?obj }"""%s.n3()
        print query
        rt = self.graph.query(query)
        self.failUnless(len(rt) == 1,"BGP should only match the 'told' BNode by name (result set size: %s)"%len(rt))
开发者ID:Ju2ender,项目名称:watchdog,代码行数:17,代码来源:test_sparql_told_bnodes.py

示例8: setUp

 def setUp(self):
     NS = u"http://example.org/"
     self.graph = ConjunctiveGraph()
     self.graph.parse(StringInputSource("""
        @prefix    : <http://example.org/> .
        @prefix rdf: <%s> .
        @prefix rdfs: <%s> .
        [ :prop :val ].
        [ a rdfs:Class ]."""%(RDF.RDFNS,RDFS.RDFSNS)), format="n3")
开发者ID:Ju2ender,项目名称:watchdog,代码行数:9,代码来源:test_sparql_told_bnodes.py

示例9: testSPARQLNotEquals

def testSPARQLNotEquals():
    NS = u"http://example.org/"
    graph = ConjunctiveGraph()
    graph.parse(StringInputSource("""
       @prefix    : <http://example.org/> .
       @prefix rdf: <%s> .
       :foo rdf:value 1.
       :bar rdf:value 2."""%RDF.RDFNS), format="n3")
    rt = graph.query("""SELECT ?node 
                        WHERE {
                                ?node rdf:value ?val.
                                FILTER (?val != 1)
                               }""",
                           initNs={'rdf':RDF.RDFNS},                           
                           DEBUG=False)
    for row in rt:        
        item = row[0]
        assert item == URIRef("http://example.org/bar")
开发者ID:Ju2ender,项目名称:watchdog,代码行数:18,代码来源:test_not_equals.py

示例10: parse

    def parse(self, source, graph):
        # we're currently being handed a Graph, not a ConjunctiveGraph
        assert graph.store.context_aware # is this implied by formula_aware
        assert graph.store.formula_aware

        conj_graph = ConjunctiveGraph(store=graph.store)
        conj_graph.default_context = graph # TODO: CG __init__ should have a default_context arg
        # TODO: update N3Processor so that it can use conj_graph as the sink
        sink = Sink(conj_graph)
        if False:
            sink.quantify = lambda *args: True
            sink.flatten = lambda *args: True
        baseURI = graph.absolutize(source.getPublicId() or source.getSystemId() or "")
        p = N3Processor("nowhere", sink, baseURI=baseURI) # pass in "nowhere" so we can set data instead
        p.userkeys = True # bah
        p.data = source.getByteStream().read() # TODO getCharacterStream?
        p.parse()
        for prefix, namespace in p.bindings.items():
            conj_graph.bind(prefix, namespace)
开发者ID:Ju2ender,项目名称:watchdog,代码行数:19,代码来源:N3Parser.py

示例11: getRdfXml

def getRdfXml(rdf):
    n3 = ""
    
    # Append the RDF namespace and print the prefix namespace mappings
    rdf['namespaces']['xh1'] = "http://www.w3.org/1999/xhtml/vocab#"
    rdf['namespaces']['rdf'] = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    for prefix, uri in rdf['namespaces'].items():
        n3 += "@prefix %s: <%s> .\n" % (prefix, uri)
        
    # Print each subject-based triple to the screen
    triples = rdf['triples']
    processed = []

    # Get all of the non-bnode subjects
    nonBnodeSubjects = getNonBnodeSubjects(triples)

    # Get all of the bnode subjects
    bnodeSubjects = getBnodeSubjects(triples)

    for subject in nonBnodeSubjects:
        subjectTriples = getTriplesBySubject(subject, triples)
        #print "PROCESSING NB SUBJECT:", subjectTriples

        if(subject not in processed):
            n3 += tripleToN3(subjectTriples, processed, triples)
        processed.append(subject)

    for subject in bnodeSubjects:
        subjectTriples = getTriplesBySubject(subject, triples)
        #print "PROCESSING BN SUBJECT:", subject
        if(subject not in processed):
            n3 += bnodeToN3(subjectTriples, processed, triples)
            n3 += " .\n"

    #print n3

    g = ConjunctiveGraph()
    g.parse(StringIO(n3), format="n3")
    rdfxml = g.serialize()

    return rdfxml
开发者ID:davidlehn,项目名称:librdfa-old,代码行数:41,代码来源:rdfa2rdfxml.py

示例12: testAggregateSPARQL

def testAggregateSPARQL():
    memStore = plugin.get('IOMemory',Store)()
    graph1 = Graph(memStore,URIRef("graph1"))
    graph2 = Graph(memStore,URIRef("graph2"))
    graph3 = Graph(memStore,URIRef("graph3"))

    for n3Str,graph in [(testGraph1N3,graph1),
                        (testGraph2N3,graph2),
                        (testGraph3N3,graph3)]:
        graph.parse(StringIO(n3Str),format='n3')

    graph4 = Graph(memStore,RDFS.RDFSNS)
    graph4.parse(RDFS.RDFSNS)
    G = ConjunctiveGraph(memStore)
    rt =  G.query(sparqlQ)
    assert len(rt) > 1
    #print rt.serialize(format='xml')
    LOG_NS = Namespace(u'http://www.w3.org/2000/10/swap/log#')
    rt=G.query(sparqlQ2,initBindings={u'?graph' : URIRef("graph3")})
    #print rt.serialize(format='json')
    assert rt.serialize('python')[0] == LOG_NS.N3Document,str(rt)
开发者ID:AuroraSkywalker,项目名称:watchdog,代码行数:21,代码来源:aggregate_graphs.py

示例13: main

def main():
	"""Main Function
	Simple command-line procedure for web2rdf."""

	if len(sys.argv) != 2:
		print "Must call with a URI parameter."
		print "Usage: %s uriSrc" % sys.argv[0]
		return

	uri = sys.argv[1]

	# Get the RDF
	wrdf = Web2Rdf(uri)
	rdf = wrdf.getRdf()

	if not rdf:
		print "No RDF returned!"
		return False

	print "Got RDF..."
	rdf = rdfString(rdf)

	# Open Storage
	print "Opening store..."
	db = "./testdb.sqlite"
	rstore = RdfStore('sqlite', db)
	rstore.open()

	print "Storing..."
	graph = Graph(rstore.get(), identifier = URIRef("http://slashdot/Test2"))
	#graph.parse("example.rdf")
	graph.parse(rdf, publicID=uri)

	graph.commit()
开发者ID:spsu,项目名称:web2rdf,代码行数:34,代码来源:fetch.py

示例14: to_rdf

    def to_rdf(self, format="settings"):
        """Convert the RdfSerializer store into RDF."""
        graph = Graph()
        for k, v in self.NAMESPACES.iteritems():
            graph.bind(k, v)

        for g in self.subgraphs:
            graph += g

        if format == "settings":
            format = settings.RDF_SERIALIZATION

        return graph.serialize(format=format)
开发者ID:spsu,项目名称:sylph,代码行数:13,代码来源:RdfSerializer.py

示例15: RdfParser

class RdfParser(object):
	"""A basic wrapper for RdfLib's RDF parser.
	This class aims to accomplish easier parsing, extraction of Models,
	etc."""

	def __init__(self, rdf, format='guess'):
		"""Init the parser with the graph string."""
		self.graph = Graph()
		if format == 'guess':
			format = self.__guess_format(rdf)
			print 'RdfParser guesses format to be: %s' % format
		try:
			self.graph.load(StringIO(rdf), format=format)
		except:
			print "Failed to parse RDF:"
			print rdf[0:100]

	def extract(self, datatype):
		"""Extract all of the data of a given datatype."""
		data = []
		ns = RdfSerializer.NAMESPACES['sylph'] # TODO: Awkward.
		for sub in self.graph.subjects(RDF.type, ns[datatype]):
			idx = str(sub)
			item = {'uri': idx}
			for pred, obj in self.graph.predicate_objects(sub):
				if pred == RDF.type:
					continue
				if obj == ns['None']:
					obj = None
				elif type(obj) == URIRef:
					obj = unicode(obj)
				elif type(obj) == Literal:
					obj = obj.toPython()
					if type(obj) == Literal: # Don't be silly, RdfLib!
						obj = unicode(obj)

				predstr = str(pred).rpartition('#')[2].rpartition('/')[2]
				item[predstr] = obj
			data.append(item)
		return data

	@staticmethod
	def __guess_format(st):
		"""Guess the format of the input string."""
		# TODO: At present, it can only guess between XML and n3, even
		# then this is a vague heuristic.
		if st.startswith('<'):
			return 'xml'
		return 'n3'
开发者ID:spsu,项目名称:sylph,代码行数:49,代码来源:RdfParser.py


注:本文中的rdflib.Graph.ConjunctiveGraph类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。