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


Python Graph.bind方法代码示例

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


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

示例1: tagdGit

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import bind [as 别名]
def tagdGit(tag,file,path):
    '''tag--Literal to be attached to blob URI with git:hasTag
       file--filename to be tagged
       path--current working directory within repo
       tagdGit queries .dgit/provenance.ttl to find most recent blob associated with filename then attached given tag to provenance
    '''

    # set up graph object
    g=Graph()
    PROV = Namespace('http://www.w3.org/prov/#')
    GIT = Namespace('http://www.example.com/ns/#')
    g.bind('prov',PROV)
    g.bind('foaf',FOAF)
    g.bind('git',GIT)

    # parse existing provenance
    g.parse(path+'/.dgit/provenance.ttl',format='turtle')

    # query blob associated with file name
    # blobID=string with URI of most recent blob associated with filename
    blobID=str(list(g.query('SELECT ?blobID WHERE {?repository prov:hadMember ?blobID .?blobID foaf:name "%s" .}'%file))[0])
    blobID=blobID.split("'")[1]

    # add tag
    g.add((URIRef(blobID),GIT.hasTag,Literal(tag)))

    # output updated provenance
    provFile=open(path+'/.dgit/provenance.ttl','w')
    print >> provFile,(g.serialize(format='turtle'))
    provFile.close()

    # stage and commit changes
    # commit message-- dgit commit: tag [filename]
    os.system('git add .dgit/provenance.ttl')
    os.system('git commit -m "dgit commit: tag %s" '%file)
开发者ID:charlesvardeman,项目名称:dGit-REU,代码行数:37,代码来源:tagDGit.py

示例2: _get_common_graph

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import bind [as 别名]
 def _get_common_graph(self, graphuri):
     # create a graph with foaf:names for all entities (publishers,
     # publication series etc) that our data mentions.
     root = URIRef(graphuri)
     g = Graph()
     g.bind("skos", SKOS)
     g.bind("foaf", FOAF)
     g.add((root, RDF.type, FOAF.Document))
     paths = set()
     bigg = Graph()
     for repo in self.repos:
         for cls in inspect.getmro(repo.__class__):
             if hasattr(cls, "alias"):
                 resourcename = "extra/%s.ttl" % cls.alias
                 if repo.resourceloader.exists(resourcename):
                     commonpath = repo.resourceloader.filename(resourcename)
                     if commonpath not in paths:
                         self.log.debug("loading data %s" % commonpath)
                         with open(commonpath) as common:
                             bigg.parse(common, format="turtle")
                         paths.add(commonpath)
     for (s, p, o) in bigg:
         if p in (FOAF.name, SKOS.prefLabel,
                  SKOS.altLabel, BIBO.identifier):
             g.add((root, FOAF.topic, s))
             # strip any typing/langtagging (because of reasons)
             if isinstance(o, Literal):
                 o = Literal(str(o))
             g.add((s, p, o))
             # try to find a type
             g.add((s, RDF.type, bigg.value(s, RDF.type)))
     return g
开发者ID:staffanm,项目名称:ferenda,代码行数:34,代码来源:resources.py

示例3: fragment

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import bind [as 别名]
def fragment(gp, broker, agora, channel, updating, gen):
    try:
        gp_match = re.search(r'\{(.*)\}', gp).groups(0)
        if len(gp_match) != 1:
            raise click.ClickException('Invalid graph pattern')

        STOA = {
            "broker_host": broker[0],
            "broker_port": broker[1],
            "agora_host": agora[0],
            "agora_port": agora[1],
            "exchange": channel[0],
            "topic_pattern": channel[1],
            "response_prefix": channel[2]
        }

        tps = re.split('\. ', gp_match[0])

        prefixes, fragment_gen = get_fragment_generator(*tps, monitoring=30, STOA=STOA, updating=updating, gen=gen)
        graph = Graph()
        for prefix in prefixes:
            graph.bind(prefix, prefixes[prefix])
            click.echo('@prefix {}: <{}> .'.format(prefix, prefixes[prefix]))
        click.echo('')

        for chunk in fragment_gen:
            if chunk is not None:
                headers, (c, s, p, o) = chunk
                triple = u'{} {} {} .'.format(s.n3(graph.namespace_manager), p.n3(graph.namespace_manager),
                                              o.n3(graph.namespace_manager))
                click.echo(triple)
    except Exception as e:
        raise click.ClickException('There was a problem with the request: {}'.format(e.message))
开发者ID:fserena,项目名称:agora-stoa-client,代码行数:35,代码来源:cli.py

示例4: register_message

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import bind [as 别名]
def register_message():
    """
    Envia un mensaje de registro al servicio de registro
    usando una performativa Request y una accion Register del
    servicio de directorio

    :param gmess:
    :return:
    """
    global mss_cnt

    gmess = Graph()

    # Construimos el mensaje de registro
    gmess.bind('foaf', FOAF)
    gmess.bind('dso', DSO)
    reg_obj = agn[InfoAgent.name+'-Register']
    gmess.add((reg_obj, RDF.type, DSO.Register))
    gmess.add((reg_obj, DSO.Uri, InfoAgent.uri))
    gmess.add((reg_obj, FOAF.Name, Literal(InfoAgent.name)))
    gmess.add((reg_obj, DSO.Address, Literal(InfoAgent.address)))
    gmess.add((reg_obj, DSO.AgentType, DSO.HotelsAgent))

    # Lo metemos en un envoltorio FIPA-ACL y lo enviamos
    gr = send_message(
            build_message(gmess, perf= ACL.request,
                      sender= InfoAgent.uri,
                      receiver= AgentDirectori.uri,
                      content= reg_obj,
                      msgcnt= mss_cnt),
            AgentDirectori.address)
    mss_cnt += 1

    return gr
开发者ID:wailingtam,项目名称:trip-planner,代码行数:36,代码来源:AgentHotel.py

示例5: prep_annotation_file

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import bind [as 别名]
    def prep_annotation_file(self, basefile):
        goldstandard = self.eval_get_goldstandard(basefile)
        baseline_set = self.eval_get_ranked_set_baseline(basefile)
        baseline_map = self.eval_calc_map(
            self.eval_calc_aps(baseline_set, goldstandard))
        print("Baseline MAP %f" % baseline_map)
        self.log.info("Calculating ranked set (pagerank, unrestricted)")
        pagerank_set = self.eval_get_ranked_set(basefile, "pagerank",
                                                age_compensation=False,
                                                restrict_cited=False)
        pagerank_map = self.eval_calc_map(
            self.eval_calc_aps(pagerank_set, goldstandard))
        print("Pagerank MAP %f" % pagerank_map)
        sets = [{'label': 'Baseline',
                 'data': baseline_set},
                {'label': 'Gold standard',
                 'data': goldstandard},
                {'label': 'PageRank',
                 'data': pagerank_set}]

        g = Graph()
        g.bind('dcterms', self.ns['dcterms'])
        g.bind('rinfoex', self.ns['rinfoex'])

        XHT_NS = "{http://www.w3.org/1999/xhtml}"
        tree = ET.parse(self.parsed_path(basefile))
        els = tree.findall("//" + XHT_NS + "div")
        articles = []
        for el in els:
            if 'typeof' in el.attrib and el.attrib['typeof'] == "eurlex:Article":
                article = str(el.attrib['id'][1:])
                articles.append(article)
        for article in articles:
            self.log.info("Results for article %s" % article)
            articlenode = URIRef(
                "http://lagen.nu/ext/celex/12008E%03d" % int(article))
            resultsetcollectionnode = BNode()
            g.add((resultsetcollectionnode, RDF.type, RDF.List))
            rc = Collection(g, resultsetcollectionnode)
            g.add((articlenode, DCTERMS["relation"], resultsetcollectionnode))
            for s in sets:
                resultsetnode = BNode()
                listnode = BNode()
                rc.append(resultsetnode)
                g.add((resultsetnode, RDF.type, RINFOEX[
                      "RelatedContentCollection"]))
                g.add((resultsetnode, DCTERMS["title"], Literal(s["label"])))
                g.add((resultsetnode, DCTERMS["hasPart"], listnode))
                c = Collection(g, listnode)
                g.add((listnode, RDF.type, RDF.List))
                if article in s['data']:
                    print(("    Set %s" % s['label']))
                    for result in s['data'][article]:
                        resnode = BNode()
                        g.add((resnode, DCTERMS["references"], Literal(result[0])))
                        g.add((resnode, DCTERMS["title"], Literal(result[1])))
                        c.append(resnode)
                        print(("        %s" % result[1]))

        return self.graph_to_annotation_file(g, basefile)
开发者ID:staffanm,项目名称:ferenda,代码行数:62,代码来源:graphanalyze.py

示例6: get

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import bind [as 别名]
	def get(self, format):
		logging.info('[API] alternative format request for [%s] from IP [%s]' %(format, os.environ['REMOTE_ADDR']))
		
		if format in SUPPORTED_OUTPUT_FORMATS:
			g = Graph()
			g.bind('void', NAMESPACES['void'], True)
			g.bind('eui', NAMESPACES['eui'], True)
			g.parse(location = 'index.html', format="rdfa") # load the RDFa-based dataset
			
			self.response.headers.add_header("Access-Control-Allow-Origin", "*") # CORS-enabled
			if format == 'rdf-xml':
				self.response.headers['Content-Type'] = 'application/rdf+xml'
				self.response.out.write(g.serialize())
			elif format == 'ttl':
				self.response.headers['Content-Type'] = 'text/turtle'
				self.response.out.write(g.serialize(format="turtle"))
			elif format == 'nt':
				self.response.headers['Content-Type'] = 'text/plain'
				self.response.out.write(g.serialize(format="nt"))
			elif format == 'json':
				# based on https://bitbucket.org/okfn/openbiblio/src/tip/rdflib/
				self.response.headers['Content-Type'] = 'application/json'
				self.response.out.write(g.serialize(None, "rdf-json-pretty"))
			elif format == 'csv':
				self.response.headers['Content-Type'] = 'text/csv'
				self.response.out.write(self.dump_csv(g))
		elif format =='':
			self.response.out.write("<div>Supported output formats or go back [<a href='/'>home</a>]:</div><ul>")
			for format in SUPPORTED_OUTPUT_FORMATS:
				self.response.out.write("".join(["<li>", "<a href='../format/", format, "'>", format , "</a></li>"]))
			self.response.out.write("</ul>")
		else:
			self.response.out.write(template.render('a404.html', None))
开发者ID:mhausenblas,项目名称:eu-institutions,代码行数:35,代码来源:handler.py

示例7: toN3

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

	graph = Graph()

	graph.bind("webtlab", "http://webtlab.it.uc3m.es/")
	graph.bind("dc", "http://purl.org/dc/elements/1.1/")

	total_changes = 0
	biggest_change_id = 0

	for change in changes_dict:
            this_change_id = change["rcid"]
            # Avoid duplicates
            if this_change_id > self.last_change:
                if this_change_id > biggest_change_id:
                    biggest_change_id = this_change_id
                change_id = URIRef("http://webtlab.it.uc3m.es/_" + str(change["rcid"]))
                graph.add( ( change_id, self.DC["date"], Literal(change["timestamp"]) ))
                graph.add( ( change_id, self.NS["title"], Literal(change["title"]) ))	  
                graph.add( ( change_id, self.NS["pageid"], Literal(str(change["pageid"])) ))	  
                total_changes += 1
	    
        self.last_change = biggest_change_id

	if total_changes > 0:
            return (total_changes, graph)
	else:
            return (total_changes, None)
开发者ID:jvrplmlmn,项目名称:ztreamy,代码行数:30,代码来源:wikipediaSensor.py

示例8: return_models_list

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import bind [as 别名]
def return_models_list():

    # currently we have an in memory description of the models list
    # in production this will be a dynamically updated rdf/jsonld triplestore

    ns = Namespace("http://openriskplatform.org/ns/doam#")

    # create an RDF graph with model data
    g = Graph()
    # identify models via their URI
    hhi = URIRef(ENTRY_POINT + "/models/hhi")
    # add model metadata
    g.add((hhi, RDF.type, ns['model']))
    g.add((hhi, FOAF.nick, Literal("hhi", lang="en")))
    g.add((hhi, FOAF.name, Literal("Hirschman")))
    g.add((hhi, ns['name'], Literal("HHI")))

    shannon = URIRef(ENTRY_POINT + "/models/shannon")
    g.add((shannon, RDF.type, ns['model']))
    g.add((shannon, FOAF.nick, Literal("sha", lang="en")))
    g.add((shannon, FOAF.name, Literal("Shannon")))
    g.add((shannon, ns['name'], Literal("Shannon")))

    # DEBUG STEP Iterate over triples in store and print them out
    if DEBUG:
        print("--- printing raw triples ---")
        for s, p, o in g:
            print((s, p, o))

    # Now that we have all general model information create json-ld output
    # Bind a few prefix, namespace pairs for more readable output
    g.bind("dc", DC)
    g.bind("foaf", FOAF)
    model_list = g.serialize(format="json-ld")
    return model_list
开发者ID:open-risk,项目名称:Open_Risk_API,代码行数:37,代码来源:model_server.py

示例9: LocalStore

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import bind [as 别名]
class LocalStore():
    '''
    This class is a wrapper for the Graph class that
    handles ontology binding and triples serialization.
    '''

    def __init__(self):
        self.g = Graph()
        self.ns = {}

    def bind_namespaces(self, namespaces):
        for ns in namespaces:
            # ns is the prefix and the key
            self.g.bind(ns, Namespace(namespaces[ns]))
            self.ns[ns] = Namespace(namespaces[ns])

    def get_namespaces(self):
        ns = []
        for namespace in self.g.namespaces():
            ns.append(namespace)
        return ns

    def get_resource(self, urn):
        return self.g.resource(urn)

    def add_triple(self, s, v, p):
        self.g.add((s, v, p))

    def serialize(self, format):
        return self.g.serialize(format=format)
开发者ID:b-cube,项目名称:pipeline-demo,代码行数:32,代码来源:btriples.py

示例10: get_info

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

        NS0 = Namespace("http://usefulinc.com/ns/doap#")
        NS1 = Namespace("http://nlp2rdf.org/")
        wrapper_id = URIRef(NS1 + "implementations/zemanta")
        BASE = Namespace(wrapper_id)

        info.bind("rdf", RDF)
        info.bind("ns0", NS0)
        info.bind("ns1", NS1)

        content = "NIF wrapper for Zemanta API."
        info.add((wrapper_id, NS0.homepage, URIRef("http://www.zemanta.com")))
        info.add(
            (
                wrapper_id,
                NS1.additionalparameter,
                Literal("You need Zemanta API key. For other parameters check Zemanta API documentation."),
            )
        )
        info.add((wrapper_id, NS1.status, Literal("NIF 2.0 compliant without RDF/XML input and JSON output")))
        info.add((wrapper_id, NS1.webserviceurl, Literal(" - Add URL here - ")))
        info.add((wrapper_id, NS1.demo, Literal(" - Add URL here - ")))
        info.add((wrapper_id, NS1.code, URIRef("https://github.com/sparkica/zem-api-wrapper")))

        return info.serialize(format=self.format, encoding="utf-8")
开发者ID:sparkica,项目名称:zem-api-wrapper,代码行数:29,代码来源:zemwrapper.py

示例11: parse_icb_graph

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import bind [as 别名]
def parse_icb_graph():
    icb_path = resource_stream("rdfconverters.resources", "mfo/ICBv1.1/icb.n3")
    icb = Graph()
    icb.parse(icb_path, format="n3")
    for n in NS:
        icb.bind(n, NS[n])
    return icb
开发者ID:monnetproject,项目名称:rdfconverters,代码行数:9,代码来源:icbnltk.py

示例12: rdf_export

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import bind [as 别名]
def rdf_export(scheme_name, export_format):
    graph = Graph()
    graph.bind('skos', 'http://www.w3.org/2004/02/skos/core#')

    schemes = store.schemes()
    scheme = schemes[scheme_name]
    ns = Namespace(scheme['uri'])

    scheme_uid = ns['Scheme']

    graph.bind(scheme['prefix'], scheme['uri'])
    graph.add((scheme_uid, RDF.type, SKOS.ConceptScheme))

    # Scheme labels
    for lang, label in scheme['labels'].items():
        graph.add((scheme_uid, SKOS.prefLabel, Literal(label, lang=lang)))

    # Concepts
    for concept in store.concept_all(scheme['prefix']):
        graph.add((ns[concept.skos_name()], RDF.type, SKOS.Concept))
        for label in concept.labels:
            graph.add((ns[concept.skos_name()],
                       SKOS[label.type],
                       Literal(label.label, lang=lang)))
    # Links
    for link in store.link_all(scheme['prefix']):
        encoded2 = link.concept2.uri.replace(' ', '_')
        graph.add((ns[link.concept1.skos_name()],
                   ns[link.relation.name],
                   ns[link.concept2.skos_name()]))
        #graph.add()
            # print link.concept1_id
            # print link.concept2_id
    return graph.serialize(format='turtle')
开发者ID:pitcons,项目名称:amarak-server,代码行数:36,代码来源:export.py

示例13: main

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import bind [as 别名]
def main():
    xls_file = resource_string('rdfconverters.resources', 'gaaps/xebrv7.xls')
    book = xlrd.open_workbook(file_contents=xls_file)

    xebr_concepts = XEBRV7Concepts(book)
    # RDF output graph
    xebr2xbrl = Graph()
    for key, ns in NS.items():
        xebr2xbrl.bind(key, ns)
    rdf_converter = RDFConverter(xebr2xbrl, xebr_concepts)

    def map_gaap(clazz_mapper, f, clazz_labels, base):
        mapper = clazz_mapper(book)
        graph = Graph().parse(f, format='n3')
        labels = clazz_labels(graph, mapper).get_labels()
        rdf_converter.add_mappings_to_graph(mapper, labels, base)


    f = resource_stream('rdfconverters.resources', 'gaaps/it.n3')
    map_gaap(ITMapper, f, ITGaapLabels, 'http://www.dfki.de/lt/xbrl_it.owl#')

    f = resource_stream('rdfconverters.resources', 'gaaps/pgc.n3')
    map_gaap(ESMapper, f, ESGaapLabels, 'http://www.dfki.de/lt/xbrl_es.owl#')

    f = resource_stream('rdfconverters.resources', 'gaaps/be.n3')
    map_gaap(BEMapper, f, BEGaapLabels, 'http://www.dfki.de/lt/xbrl_be.owl#')


    util.write_graph(xebr2xbrl, '/tmp/xebr2xbrl.n3')
开发者ID:monnetproject,项目名称:rdfconverters,代码行数:31,代码来源:xebr2xbrl_generator.py

示例14: rdf_from_sources

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import bind [as 别名]
	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" and "pretty-xml", as well as "turtle" and "n3" are synonyms.
		@return: a serialized RDF Graph
		@rtype: string
		"""
		if rdflib.__version__ >= "3.0.0" :
			graph = Graph()
		else :
			# We may need the extra utilities for older rdflib versions...
			try :
				from pyRdfaExtras import MyGraph
				graph = MyGraph()
			except :
				graph = Graph()

		for prefix in _bindings :
			graph.bind(prefix, Namespace(_bindings[prefix]))

		# the value of rdfOutput determines the reaction on exceptions...
		for name in names :
			self.graph_from_source(name, graph, rdfOutput)
		return graph.serialize(format=outputFormat)
开发者ID:RDFLib,项目名称:pymicrodata,代码行数:28,代码来源:__init__.py

示例15: infoagent_search_message

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import bind [as 别名]
def infoagent_search_message(addr, ragn_uri):
    """
    Envia una accion a un agente de informacion
    """
    global mss_cnt
    logger.info('Hacemos una peticion al servicio de informacion')

    gmess = Graph()

    # Supuesta ontologia de acciones de agentes de informacion
    IAA = Namespace('IAActions')

    gmess.bind('foaf', FOAF)
    gmess.bind('iaa', IAA)
    reg_obj = agn[AgentePersonal.name + '-info-search']
    gmess.add((reg_obj, RDF.type, IAA.Search))

    msg = build_message(gmess, perf=ACL.request,
                        sender=AgentePersonal.uri,
                        receiver=ragn_uri,
                        msgcnt=mss_cnt)
    gr = send_message(msg, addr)
    mss_cnt += 1
    logger.info('Recibimos respuesta a la peticion al servicio de informacion')

    return gr
开发者ID:AlbertSuarez,项目名称:Practica-ECSDI,代码行数:28,代码来源:SimplePersonalAgent.py


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