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


Python ConjunctiveGraph.triples方法代码示例

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


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

示例1: ConvertToRDFN3

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
def ConvertToRDFN3 (filename, destinationFileName):
    _graph = ConjunctiveGraph()
    _graph.parse(filename, format="nt")
    _graph.triples((None, None, None))

    of = open(destinationFileName, "wb")
    of.write(_graph.serialize(format="n3"))
    of.close()
开发者ID:bordonhos,项目名称:WS-TP3,代码行数:10,代码来源:converter.py

示例2: ConvertToSQLLITE

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
def ConvertToSQLLITE (filename,destinationFileName):

    _graph = ConjunctiveGraph()
    _graph.parse(filename, format="nt")
    _graph.triples((None, None, None))


    sql = ConjunctiveGraph('SQLite')
    sql.open(destinationFileName, create=True)

    for t in _graph.triples((None,None,None)):
        sql.add(t)

    sql.commit()
    sql.close()
开发者ID:bordonhos,项目名称:WS-TP3,代码行数:17,代码来源:converter.py

示例3: instance_view_jsonld

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
def instance_view_jsonld(request):
    from assembl.semantic.virtuoso_mapping import AssemblQuadStorageManager
    from rdflib import URIRef, ConjunctiveGraph
    ctx = request.context
    user_id = authenticated_userid(request) or Everyone
    permissions = get_permissions(
        user_id, ctx.get_discussion_id())
    instance = ctx._instance
    if not instance.user_can(user_id, CrudPermissions.READ, permissions):
        return HTTPUnauthorized()
    discussion = ctx.get_instance_of_class(Discussion)
    if not discussion:
        raise HTTPNotFound()
    aqsm = AssemblQuadStorageManager()
    uri = URIRef(aqsm.local_uri() + instance.uri()[6:])
    d_storage_name = aqsm.discussion_storage_name(discussion.id)
    v = get_virtuoso(instance.db, d_storage_name)
    cg = ConjunctiveGraph(v, d_storage_name)
    result = cg.triples((uri, None, None))
    #result = v.query('select ?p ?o ?g where {graph ?g {<%s> ?p ?o}}' % uri)
    # Something is wrong here.
    triples = '\n'.join([
        '%s %s %s.' % (uri.n3(), p.n3(), o.n3())
        for (s, p, o) in result
        if '_with_no_name_entry' not in o])
    return aqsm.quads_to_jsonld(triples)
开发者ID:Lornz-,项目名称:assembl,代码行数:28,代码来源:__init__.py

示例4: catalyst_graph_for

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
def catalyst_graph_for(file):
    if file.startswith("/"):
        file = "file://" + file
    logging.info("InferenceStore catalyst_graph_for started")

    # quads = jsonld.to_rdf(file, {'format': 'application/nquads'})
    logging.info("InferenceStore JSON-LD loaded")

    g = ConjunctiveGraph()
    g.namespace_manager = namespace_manager
    # g.parse(data=quads, format='nquads')
    g.load(file, format="json-ld")
    logging.info("InferenceStore base graph loaded")

    f = FuXiInferenceStore.get_instance()

    # get the inference engine
    cl = f.get_inference(g)
    logging.info("InferenceStore inference graph loaded")

    union_g = rdflib.ConjunctiveGraph()

    for s, p, o in g.triples((None, None, None)):
        union_g.add((s, p, o))

    for s, p, o in cl.triples((None, None, None)):
        union_g.add((s, p, o))

    logging.info("InferenceStore union graph prepared")

    return union_g
开发者ID:mapofemergence,项目名称:edgesense,代码行数:33,代码来源:inference.py

示例5: generate

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
    def generate(cls, utensils):
        graph = ConjunctiveGraph()
        load_rdf_file(STORE['actions'], graph)

        for utensil in utensils:
            for action in utensil.actions:
                map(rdfSubject.db.add, graph.triples((action.resUri, None, None)))
开发者ID:poulp,项目名称:randomfoOd,代码行数:9,代码来源:generators.py

示例6: get_ref_vocabs

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
def get_ref_vocabs():
    reflist = {}
    if not os.path.isfile(ag.vocabulariesref):
        return reflist
    graph = Graph()
    graph.parse(ag.vocabulariesref)
    for s, p, o in graph.triples((None, namespaces['dcterms']['isVersionOf'], None)):
        reflist[str(s)] = str(o)
    return reflist
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:11,代码来源:rdf_helper.py

示例7: __isIncluded

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
 def __isIncluded(self, targetURI, returnedDocURI):
     try:
         g = ConjunctiveGraph()
         g.parse(returnedDocURI, format=self.result['format'])
         subList = list(g.triples((rdflib.URIRef(targetURI), None, None)))
         preList = list(g.triples((None, rdflib.URIRef(targetURI), None)))
         objList = list(g.triples((None, None , rdflib.URIRef(targetURI)))) 
         if len(subList)==0 and len(preList)==0 and len(objList)==0:
             return 0
         else:
             subList.extend(preList)
             subList.extend(objList)
             self.result['relatedTriple']= subList
             return 1
     except Exception, e:
         print e
         self.result['isException'] = 1
         self.result['exceptionType']= 'RDF Graph Load Exception'
         self.result['exceptionMsg']=repr(e)
         return 0
开发者ID:yangsquared,项目名称:HyperThing,代码行数:22,代码来源:HttpTest.py

示例8: from_string

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
 def from_string(self, uri, text, format="xml", encoding="utf-8"):
     self.reset()
     self.set_uri(uri)
     t = TextInputSource(text, system_id=uri)
     t.setEncoding(encoding)
     g = ConjunctiveGraph(identifier=self.uri)
     g = g.parse(t, format)
     for prefix, ns in g.namespaces():
         self.add_namespace(prefix, ns)
     for s,p,o in g.triples((self.uri, None, None)):
         self.add_triple(p, o)
开发者ID:benosteen,项目名称:RDFobject,代码行数:13,代码来源:rdfobject.py

示例9: from_url

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
 def from_url(self, url, uri=None, format="xml",  encoding="utf-8"):
     self.reset()
     if not uri:
         self.set_uri(url)
     else:
         self.set_uri(uri)
     g = ConjunctiveGraph(identifier=self.uri)
     g = g.parse(url, format)
     for prefix, ns in g.namespaces():
         self.add_namespace(prefix, ns)
     for s,p,o in g.triples((self.uri, None, None)):
         self.add_triple(p, o)
开发者ID:benosteen,项目名称:RDFobject,代码行数:14,代码来源:rdfobject.py

示例10: get

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
 def get(self):
     g = ConjunctiveGraph()
     addTrig(g, "http://bang:9099/graph")
     maxMeters = 65000
     pts = []
     print "loaded", len(g)
     for s,p,o in g.triples((None, MAP['distanceToHomeM'], None)):
         pts.append(dict(who=s,
                         frac=float(o) / maxMeters,
                         distanceToHomeM=o,
                         displayMilesDistance="%.1f miles" %
                         (float(o) * 0.000621371)))
     self.write(json.dumps({'pts': pts}))
开发者ID:,项目名称:,代码行数:15,代码来源:

示例11: from_string

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
    def from_string(self, rdf_manifest_string, format="xml"):
        t = TextInputSource(rdf_manifest_string)
        g = ConjunctiveGraph()
        g = g.parse(t, format)
        
        for s,p,o in g.triples((None, None, None)):
            if s not in self.items:
                self.items.append(s)
            if p == NAMESPACES['rdf']['type']:
                self.items_rdfobjects.setdefault(s,RDFobject(uri=s)).add_type(o)
            else:
                self.items_rdfobjects.setdefault(s,RDFobject(uri=s)).add_triple(p, o)

        for prefix, ns in g.namespaces():
            self.add_namespace(prefix ,ns)
开发者ID:benosteen,项目名称:RDFobject,代码行数:17,代码来源:manifest.py

示例12: get_vocab_editorial_note

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
def get_vocab_editorial_note(vocabprefix):
    vocab_uri = URIRef("http://vocab.ox.ac.uk/%s"%vocabprefix)
    vocabdir = os.path.join(ag.vocabulariesdir, vocabprefix)
    vocabstatusfile = os.path.join(vocabdir, "status.rdf")
    msgs = []
    if not os.path.isfile(vocabstatusfile):
        return msgs
    graph = Graph()
    graph.parse(vocabstatusfile)
    for s, p, o in graph.triples((None, namespaces['skos']['editorialNote'], None)):
        nm = None
        for n in graph.objects(URIRef(s), namespaces['nfo']['fileName']):
            nm = str(n)
        msgs.append((str(o), nm))
    return msgs
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:17,代码来源:rdf_helper.py

示例13: test_jsonld

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
def test_jsonld():
    # generate shared canvase json-ld
    tei_file = "sga/data/tei/ox/ox-frankenstein_notebook_c1.xml"
    manifest_uri = 'http://example.com/frankenstein.json'
    m = Manifest(tei_file, manifest_uri)
    jsonld = m.jsonld()
    open('test.jsonld', 'w').write(json.dumps(jsonld, indent=2))

    # find the manifest
    manifest = None
    for r in jsonld['@graph']:
        if '@type' in r and r['@type'] == 'sc:Manifest':
            manifest = r
    assert manifest

    # check for images
    assert 'images' in manifest

    # check for canvases
    assert 'canvases' in manifest

    # get the sequence
    assert 'sequences' in manifest
    seq = get(jsonld, manifest['sequences'][0])

    # first canvas
    assert 'first' in seq
    canvas = get(jsonld, seq['first'])
    assert canvas['label'] == '1r'

    # check the content annotations
    assert count_type(jsonld, 'sc:ContentAnnotation') == 90
   
    # css should be there
    assert count_type(jsonld, 'cnt:ContentAsText') == 61

    # parse the json-ld as rdf
    register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser')
    g = ConjunctiveGraph()
    jsonld_str = json.dumps(jsonld)
    g.parse(data=jsonld_str, format='json-ld')

    # quick sanity check the graph
    assert g.value(URIRef('http://example.com/frankenstein.json'), RDF.type) == URIRef('http://www.shared-canvas.org/ns/Manifest')
    line_anns = list(g.triples((None, RDF.type, SGA.LineAnnotation)))
    assert len(line_anns) == 638
开发者ID:umd-mith,项目名称:unbind,代码行数:48,代码来源:test.py

示例14: GraphCache

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
class GraphCache(object):

    def __init__(self, cachedir):
        self.graph = ConjunctiveGraph()
        self.mtime_map = {}
        self.cachedir = cachedir
        if not os.path.isdir(cachedir):
            os.makedirs(cachedir)

    def load(self, url):
        src = VOCAB_SOURCE_MAP.get(str(url), url)
        if os.path.isfile(url):
            context_id = create_input_source(url).getPublicId()
            last_vocab_mtime = self.mtime_map.get(url)
            vocab_mtime = os.stat(url).st_mtime
            if not last_vocab_mtime or last_vocab_mtime < vocab_mtime:
                logger.debug("Parse file: '%s'", url)
                self.mtime_map[url] = vocab_mtime
                # use CG as workaround for json-ld always loading as dataset
                graph = ConjunctiveGraph()
                graph.parse(src, format=guess_format(src))
                self.graph.remove_context(context_id)
                for s, p, o in graph:
                    self.graph.add((s, p, o, context_id))
                return graph
        else:
            context_id = url

        if any(self.graph.triples((None, None, None), context=context_id)):
            logger.debug("Using context <%s>" % context_id)
            return self.graph.get_context(context_id)

        cache_path = self.get_fs_path(url)
        if os.path.exists(cache_path):
            logger.debug("Load local copy of <%s> from '%s'", context_id, cache_path)
            return self.graph.parse(cache_path, format='turtle', publicID=context_id)
        else:
            logger.debug("Fetching <%s> to '%s'", context_id, cache_path)
            graph = self.graph.parse(src,
                    format='rdfa' if url.endswith('html') else None)
            with open(cache_path, 'w') as f:
                graph.serialize(f, format='turtle')
            return graph

    def get_fs_path(self, url):
        return os.path.join(self.cachedir, quote(url, safe="")) + '.ttl'
开发者ID:niklasl,项目名称:vim-rdf,代码行数:48,代码来源:rdfns.py

示例15: run

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import triples [as 别名]
	def run(self):
		ontologies = self.ontologies

		# Definition of namespaces
		# Uncomment if needed
		NS_owl =  Namespace("http://www.w3.org/2002/07/owl#")
		NS_rdfs =  Namespace("http://www.w3.org/2000/01/rdf-schema#")
		NS_xsd =  Namespace("http://www.w3.org/2001/XMLSchema#")
		NS_rdf =  Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
		NS_mcf =  Namespace("http://www.mycorporisfabrica.org/ontology/mcf.owl#")

		g1 = ConjunctiveGraph()
		g2 = ConjunctiveGraph()
		g1.parse(ontologies[0], format=guess_format(ontologies[0]))
		g2.parse(ontologies[1], format=guess_format(ontologies[1]))
		listDiff = ConjunctiveGraph()
		listDiff = g1 ^ g2

		global listNames, listSizes

		for s,p,o in g1.triples((None, None, None)):
			item = ""
			#item += "[[ "+str(s)+" ]]\t[[ "+str(p)+" ]]\t[[ "+str(o)+" ]]"
			item +=str(s)+" || "+str(p)+" || "+str(o)
			self.emit(SIGNAL('addListItem(QString)'), item)

		ontologySplit = ontologies[0].split('/')
		ontologyName=ontologySplit[len(ontologySplit)-1]
		listNames.append(ontologyName)
		listSizes.append(str(len(g1)))
		tab["Ontology"] = listNames
		tab["Size"] = listSizes

		self.emit(SIGNAL('update_table(PyQt_PyObject)'), tab)

		ontologySplit = ontologies[1].split('/')
		ontologyName=ontologySplit[len(ontologySplit)-1]
		listNames.append(ontologyName)
		listSizes.append(str(len(g2)))
		tab["Ontology"] = listNames
		tab["Size"] = listSizes

		self.emit(SIGNAL('update_table(PyQt_PyObject)'), tab)
开发者ID:LilyOfTheWest,项目名称:OntologyTool,代码行数:45,代码来源:fusion_adv_thread.py


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