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


Python Graph.triples方法代码示例

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


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

示例1: main

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
def main():
    "Detect all orphan files and entries"
    g = Graph()
    for manifest in [MANIFEST_PATH, MANIFEST_SYNTAX_PATH,
                     MANIFEST_TURTLE_LDPATCH_PATH,]:
        g.load(manifest, format="turtle")
        LOG.debug("loaded %s", manifest)
    for manifest in [MANIFEST_TURTLE_PATH,]:
        if exists(manifest):
            g.load(manifest, format="turtle")
            LOG.debug("loaded %s", manifest)

    # looking for entries that are not part of an mf:entry list
    for subj, _, _ in g.triples((None, MF.action, None)):
        if not list(g.triples((None, RDF.first, subj))):
            print subj

    # looking for files that are not referenced
    FILTER = regex(r'.*\.(ttl|nt|ldpatch)$')
    for foldername in (TESTSUITE_PATH, TURTLE_PATH):
        for filename in listdir(foldername):
            if not FILTER.match(filename):
                continue
            if filename.startswith("manifest"):
                continue
            iri = p2i(join(foldername, filename))
            if not list(g.triples((None, None, iri))):
                print iri

    # checking that all entries have the correct name
    for subj, _, obj in g.triples((None, MF.name, None)):
        if subj.rsplit("#",1)[1] != unicode(obj):
            print "WRONG NAME for ", subj
开发者ID:pchampin,项目名称:ld-patch-testsuite,代码行数:35,代码来源:check.py

示例2: get_actions_from_utensil

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
def get_actions_from_utensil(label):
    """ return a list of url's image found by
        a label query on dbpedia
    """
	# actions
    headers = {"Accept": "application/rdf+xml"}
    req = urllib2.Request(GET_UTENSIL_URL, headers=headers)
    response = urllib2.urlopen(req)
    graph = Graph()
    graph.parse(data=response.read(), format="xml")

	# actions
    req = urllib2.Request(GET_ACTION_URL, headers=headers)
    response = urllib2.urlopen(req)
    graph_action = Graph()
    graph_action.parse(data=response.read(), format="xml")
    list_actions = []

    for s, p, o in graph.triples((None, RDF.type, NS1.Utensil)):
        if s.__str__() == label:
            for a, b, c in graph.triples((s, NS1.Action, None)):
			#	list_actions.append(Action(graph_action.value(c, RDFS.label), c))
                list_actions.append({"label":graph_action.value(c, RDFS.label),"uri":c.__str__()})
				
    return list_actions
开发者ID:poulp,项目名称:randomfoOd,代码行数:27,代码来源:utils.py

示例3: set_meaning_2

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
	def set_meaning_2(self,lang):

		import rdflib
		from rdflib import URIRef
		from rdflib import Graph
		means = URIRef("http://lexvo.org/ontology#means")
		seeAlso = URIRef("http://www.w3.org/2000/01/rdf-schema#seeAlso")

		g = Graph()
		parse = True		
		try:
			#print "http://www.lexvo.org/data/term/" + lang + "/" + urllib.quote(self.name.encode('utf-8'))
			g.parse("http://www.lexvo.org/data/term/" + lang + "/" + urllib.quote(self.name.encode('utf-8')))
		except:
			parse = False

		self.meanings = []
		if parse:
			#out = self.name.encode('utf-8')

			if (None, seeAlso, None) in g:
				#print "See Also found!"
				for s,p,o in g.triples((None,seeAlso,None)):
					#print o
					#out = out + ";" + o.encode('utf-8')
					self.meanings.append(o.encode('utf-8'))

			if (None, means, None) in g:
				#print "Meaning found!"
				for s,p,o in g.triples((None,means,None)):
					#print o
					#out = out + ";" + o.encode('utf-8')
					self.meanings.append(o.encode('utf-8'))
开发者ID:alantygel,项目名称:StodAp,代码行数:35,代码来源:model.py

示例4: makeBots

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
def makeBots(application, configFilename):
    bots = {}
    g = Graph()
    g.parse(configFilename, format='n3')
    for botNode, botJid, password, name, birthdate in g.query("""
      SELECT DISTINCT ?botNode ?botJid ?password ?name ?birthdate WHERE {
        ?botNode a db:DiaryBot;
          rdfs:label ?name;
          foaf:jabberID ?botJid .
        OPTIONAL {
          ?botNode db:password ?password .
        }
        OPTIONAL {
         ?botNode bio:event [ a bio:Birth; bio:date ?birthdate ] .
        }
      }""", initNs=INIT_NS):
        if birthdate is not None:
            birthdate = parse(birthdate).replace(tzinfo=tz.gettz('UTC'))
        b = Bot(str(name), botJid, password,
                set(g.objects(botNode, DB['owner'])),
                birthdate=birthdate,
                autotexts=list(map(unicode, g.objects(botNode, DB['autotext'])))
        )
        if hasattr(b, 'client'):
            b.client.setServiceParent(application)
        bots[str(name)] = b

    for s,p,o in g.triples((None, FOAF['jabberID'], None)):
        _agent[str(o)] = s

    for s,p,o in g.triples((None, FOAF['name'], None)):
        _foafName[s] = o

    return bots
开发者ID:,项目名称:,代码行数:36,代码来源:

示例5: test_parse_rdfa

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

        bob = AffiliationFactory.create(name='Bob')

        lib_object = LibraryFactory()
        lib_object.affiliations.add(bob)
        fc = FlowCellFactory()
        lanes = []
        for i in range(1,3):
            # mark even lanes as failed.
            lanes.append(LaneFactory(flowcell=fc,
                                     lane_number=i,
                                     library=lib_object,
                                     status = 0 if i % 2 == 0 else None
            ))
        url = reverse('library_detail', args=(lib_object.id,))
        ## request = self.request.get(url)
        ## lib_response = library(request)
        lib_response = self.client.get(url)
        lib_body = smart_str(lib_response.content)
        self.assertNotEqual(len(lib_body), 0)

        model.parse(data=lib_body, format='rdfa', publicID='http://localhost'+url)

        # http://jumpgate.caltech.edu/wiki/LibraryOntology#affiliation>
        self.check_literal_object(model, ['Bob'], p=libraryOntology['affiliation'])
        self.check_literal_object(model,
                                  ['experiment type name'],
                                  p=libraryOntology['experiment_type'])
        self.check_literal_object(model, [400], p=libraryOntology['gel_cut'])
        self.check_literal_object(model,
                                  ['microfluidics bot 7321'],
                                  p=libraryOntology['made_by'])
        self.check_literal_object(model,
                                  [lib_object.library_name],
                                  p=libraryOntology['name'])
        self.check_literal_object(model,
                                  [lib_object.library_species.scientific_name],
                                  p=libraryOntology['species_name'])

        library_url = 'http://localhost/library/{}/'.format(lib_object.id)
        lane_url = 'http://localhost/lane/{}'
        for uri, term, expected in [
                (library_url, libraryOntology['has_lane'], lane_url.format(lanes[0].id)),
                (library_url, libraryOntology['has_failed_lane'], lane_url.format(lanes[1].id))]:
            triples = list(model.triples((URIRef(uri), term, None)))
            self.assertEqual(len(triples), 1)
            self.assertEqual(triples[0][2], URIRef(expected))

        for uri, expected in [(lane_url.format(lanes[0].id), ''),
                              (lane_url.format(lanes[1].id), 'Failed')]:
            triples = list(
                model.triples((
                    URIRef(uri),
                    libraryOntology['status'],
                    None)))
            self.assertEqual(len(triples), 1)
            self.assertEqual(triples[0][2].toPython(), expected)
开发者ID:detrout,项目名称:htsworkflow,代码行数:61,代码来源:test_samples.py

示例6: parse_tag_list

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
def parse_tag_list(data_url, data_format, tag_limit):
    """Parses a SKOS vocabulary file and forms a list of tag strings from the Finnish labels of each SKOS concept."""

    tag_list = []
    graph = Graph()
    graph.parse(data_url, format=data_format)

    for concept, concept_pred, concept_obj in graph.triples((None, RDF.type, SKOS.Concept)):
        for label, label_pred, label_obj in graph.triples((concept, SKOS.prefLabel, None)):
            if len(tag_list) < tag_limit:
                if label_obj.language == 'fi':
                    tag_list.append(unicode(label_obj))
            else:
                break
    return tag_list
开发者ID:haphut,项目名称:ytp,代码行数:17,代码来源:tasks.py

示例7: testStms

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
def testStms(queries,filename):
    g = Graph()
    g.parse(filename, format="nt")    
    allSubj = g.triples()
    unique = set()
    total = 0
    
    for s in allSubj:
        if s not in unique:
            total = total +1
    
    print total
    
    stms = set()
    
    for q in queries:
        print "Query: " + q
        results = g.query(q)       
        for row in results:
            stm = row[0]
            if stm not in stms:
                stms.add(stm)                
    
    coverage = len(stms)/float(total)
    print len(stms)
    print coverage
    
    return
开发者ID:junszhao,项目名称:ProvQ,代码行数:30,代码来源:prov-query-generator.py

示例8: makerdf

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
def makerdf(workflow, wf, ctx):
    # type: (Union[str, unicode], Union[List[Dict[unicode, Any]], Dict[unicode, Any]], Loader.ContextType) -> Graph
    prefixes = {}
    for k,v in ctx.iteritems():
        if isinstance(v, dict):
            url = v["@id"]
        else:
            url = v
        doc_url, frg = urlparse.urldefrag(url)
        if "/" in frg:
            p, _ = frg.split("/")
            prefixes[p] = u"%s#%s/" % (doc_url, p)

    if isinstance(wf, list):
        for entry in wf:
            entry["@context"] = ctx
    else:
        wf["@context"] = ctx
    g = Graph().parse(data=json.dumps(wf), format='json-ld', location=workflow)

    # Bug in json-ld loader causes @id fields to be added to the graph
    for s,p,o in g.triples((None, URIRef("@id"), None)):
        g.remove((s, p, o))

    for k2,v2 in prefixes.iteritems():
        g.namespace_manager.bind(k2, v2)

    return g
开发者ID:curoverse,项目名称:cwltool,代码行数:30,代码来源:cwlrdf.py

示例9: parse

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
def parse(page):
    g = Graph()
    g.parse(data=page, format="microdata")

    places = ((s, schema(o)) for s, p, o in g.triples((None, RDF.type, None))
              if is_place(o))
    return [collect(g, place, category) for place, category in places]
开发者ID:pombredanne,项目名称:Ente,代码行数:9,代码来源:parser.py

示例10: register

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
def register():
    """
    Entry point del agente que recibe los mensajes de registro

    :return:
    """
    global dsgraph
    global mss_cnt
    #cola1.put('zzz')
    message= request.args['content']
    gm = Graph()
    gr = Graph()
    gr.bind('acl',ACL)
    gm.parse(data=message)
    print gm.serialize(format='turtle')
    perf = gm.triples( (None,  RDF.type, sa)) # Obtenemos la performativa
    if perf is None:
        gr.add((ACL['not-understood'], RDF.type, sa))
    else:
        aresp= gm.subject_objects(FOAF.name)
        a,n = aresp.next()
        print a, n
        ms = ACL['message{:{fill}4d}'.format(mss_cnt, fill='0')]
        mss_cnt += 1
        gr.add((ms, RDF.type, sa))
        gr.add((ms, ACL.performative, ACL.confirm))
        gm.add((agn.juan, FOAF.name, Literal('RegisterAgent')))
        gm.add((ms, ACL.sender, agn.RegisterAgent))
        #dsgraph.open('./myRDFLibStore')
        dsgraph += gm
    return gr.serialize(format='xml')
开发者ID:wailingtam,项目名称:trip-planner,代码行数:33,代码来源:RegisterAgent.py

示例11: RDFLibBackend

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
class RDFLibBackend(Backend):
    def __init__(self, graph_uri):
        self.graph = Graph().parse(graph_uri, format="turtle")

    def triples(self, triple_pattern, start_index=''):

        triples = sorted(
            self.graph.triples(triple_pattern)
        )
        total_triples = len(triples)
        try:
            start = int(start_index)
        except:
            start = 0

        page_size = 100
        next_start = start + page_size

        if total_triples < next_start:
            next_start = None


        return TriplesResult(
            total_triples,
            next_start,
            triples[start:start+page_size]
        )
开发者ID:ericmoritz,项目名称:python-ldf-server,代码行数:29,代码来源:rdflib_backend.py

示例12: test_concurrent2

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
def test_concurrent2(): 
    dns = Namespace(u"http://www.example.com/")

    store = plugin.get("IOMemory", Store)()
    g1 = Graph(store=store)
    g2 = Graph(store=store)

    g1.add((dns.Name, dns.prop, Literal(u"test")))
    g1.add((dns.Name, dns.prop, Literal(u"test2")))
    g1.add((dns.Name, dns.prop, Literal(u"test3")))

    n = len(g1)
    i = 0

    for t in g1.triples((None, None, None)):
        i+=1
        g2.add(t)
        # next line causes problems because it adds a new Subject that needs
        # to be indexed  in __subjectIndex dictionary in IOMemory Store.
        # which invalidates the iterator used to iterate over g1
        g2.add((dns.Name1, dns.prop1, Literal(u"test")))
        g2.add((dns.Name1, dns.prop, Literal(u"test")))
        g2.add((dns.Name, dns.prop, Literal(u"test4")))

    assert i == n
开发者ID:Dataliberate,项目名称:rdflib,代码行数:27,代码来源:test_iomemory.py

示例13: _process_rest_services

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
 def _process_rest_services(self, rest_file_path):
     rdf_graph = Graph()
     rdf_graph.parse(rest_file_path, format="n3")
     
     for t in rdf_graph.triples((None, http_ns.request, None)):
         rc = self._process_lemmas_rest(t[2])
         self.calls[ str(t[0]) ] = rc
开发者ID:gomezgoiri,项目名称:actuationInSpaceThroughRESTdesc,代码行数:9,代码来源:rest_parser.py

示例14: RewriteGraph

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
class RewriteGraph(Graph):
    def __init__(
        self, store='default', identifier=None, rewritten_identifier=None, namespace_manager=None
    ):
        super().__init__(
            store=store, identifier=rewritten_identifier, namespace_manager=namespace_manager
        )
        self.__graph = Graph(
            store=store, identifier=identifier, namespace_manager=namespace_manager
        )

    def triples(self, triple):
        return self.__graph.triples(triple)

    def add(self, triple_or_quad):
        raise ModificationException()

    def addN(self, triple_or_quad):
        raise ModificationException()

    def remove(self, triple_or_quad):
        raise ModificationException()

    def __iadd__(self, other):
        raise ModificationException()

    def __isub__(self, other):
        raise ModificationException()

    def parse(self, source, publicID=None, format="xml", **args):
        raise ModificationException()

    def __len__(self):
        return len(self.__graph)
开发者ID:AKSW,项目名称:QuitStore,代码行数:36,代码来源:graphs.py

示例15: Agent

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import triples [as 别名]
class Agent(object):
    
    http_namespace = Namespace("http://www.w3.org/2011/http#")
    dul_namespace = Namespace("http://www.loa.istc.cnr.it/ontologies/DUL.owl#")
    dbpedia_namespace = Namespace("http://dbpedia.org/ontology/")
    
    def __init__(self, file_path):
        n3_ordered = self._order_triples_alphabetically(file_path)
        self.g = Graph()
        #self.g.parse(file_path, format="n3")
        self.g.parse(StringIO(n3_ordered), format="n3")
        print self.g.serialize(format="n3")
    
    def _order_triples_alphabetically(self, file_path):        
        with open (file_path, "r") as myfile:
            ret = ""
            to_order = []
            for line in myfile.read().splitlines(): # .sort()
                if line.startswith("@prefix"):
                    ret = "%s\n%s" % (ret, line)
                elif line.startswith("#"):
                    pass # ignore
                else:
                    to_order.append(line)
            
            for line in sorted(to_order):
                ret = "%s\n%s" % (ret, line)
            return ret
    
    def get_requests_in_order(self):
        t = self.g.triples((None, Agent.http_namespace["requestURI"], None ) )
        for trip in t:
            print trip
            
    def get_goal(self):
        # <myphoto.jpg> dbpedia-owl:thumbnail
        # ?outputvalue  dul:hasDataValue  :t19 .
        #t = self.g.triples((None, Agent.dul_namespace["hasDataValue"], None ) )
        return self.g.triples((None, Agent.dbpedia_namespace["thumbnail"], None ) )
            
    def get_path_to_goal(self):
        # <myphoto.jpg> dbpedia-owl:thumbnail
        # ?outputvalue  dul:hasDataValue  :t19 .
        #t = self.g.triples((None, Agent.dul_namespace["hasDataValue"], None ) )
        t = self.g.triples((None, Agent.dbpedia_namespace["thumbnail"], None ) )
        for trip in t:
            print trip
开发者ID:gomezgoiri,项目名称:actuationInSpaceThroughRESTdesc,代码行数:49,代码来源:agent.py


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