• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python rdflib.URIRef类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: get_synthesis_contributors

    def get_synthesis_contributors(self, id_only=True):
        # author of important extracts
        from .idea_content_link import Extract
        from .auth import AgentProfile
        from .post import Post
        from sqlalchemy.sql.functions import count
        local_uri = AssemblQuadStorageManager.local_uri()
        discussion_storage = \
            AssemblQuadStorageManager.discussion_storage_name()

        idea_uri = URIRef(self.uri(local_uri))
        clause = '''select distinct ?annotation where {
            %s idea:includes* ?ideaP .
            ?annotation assembl:resourceExpressesIdea ?ideaP }'''
        extract_ids = [x for (x,) in self.db.execute(
            SparqlClause(clause % (
                idea_uri.n3(),),
                quad_storage=discussion_storage.n3()))]
        r = list(self.db.query(AgentProfile.id, count(Extract.id)).join(
            Post, Post.creator_id==AgentProfile.id).join(Extract).filter(
            Extract.important == True, Extract.id.in_(extract_ids)))
        r.sort(key=lambda x: x[1], reverse=True)
        if id_only:
            return [AgentProfile.uri_generic(a) for (a, ce) in r]
        else:
            ids = [a for (a, ce) in r]
            order = {id: order for (order, id) in enumerate(ids)}
            agents = self.db.query(AgentProfile).filter(AgentProfile.id.in_(ids)).all()
            agents.sort(key=lambda a: order[a.id])
            return agents
开发者ID:Lornz-,项目名称:assembl,代码行数:30,代码来源:idea.py


示例2: process_journal

def process_journal(records, writer, mappings):
    record, fields = majority_vote(records, ('Journal',), mappings)

    if record.get('issn'):
        uri = URIRef('urn:issn:%s' % record['issn'])
        graph_uri = URIRef('/graph/issn/%s' % record['issn'])
    elif record.get('x-nlm-ta'):
        uri = URIRef('/id/journal/%s' % sluggify(record['x-nlm-ta']))
        graph_uri = URIRef('/graph/journal/%s' % sluggify(record['x-nlm-ta']))
    elif record.get('name'):
        uri = URIRef('/id/journal/%s' % sluggify(record['name']))
        graph_uri = URIRef('/graph/journal/%s' % sluggify(record['name']))
    else:
        sys.stderr.write("Unidentifiable: %s" % record)
        return

    for id, _ in fields['id']:
        mappings['id'][id] = uri
        mappings['journal'][uri] = graph_uri.split('/', 3)[-1]

    writer.send((uri, RDF.type, FABIO.Journal, graph_uri))

    for key, predicate in JOURNAL_DATA_PROPERTIES:
        if key in record:
            writer.send((uri, predicate, Literal(record[key]), graph_uri))

    if isinstance(record.get('publisher'), URIRef):
        writer.send((uri, DCTERMS.publisher, record['publisher'], graph_uri))
开发者ID:opencitations,项目名称:PubMed-OA-network-analysis-scripts,代码行数:28,代码来源:bibjson_rdf.py


示例3: view

def view(rtype, rid):
    if '.' in rid:
        rid, suffix = rid.rsplit('.', 1)
    else:
        suffix = None
    path = rtype + '/' + rid

    uri = URIRef(app.config['RESOURCE_BASE'] + path)
    #if template:
    services = app.config['SERVICES']
    rq = render_template("queries/%s.rq" % rtype,
            prefixes=RQ_PREFIXES, this=uri.n3(), services=services)

    fmt = _conneg_format(suffix)
    if fmt == 'rq':
        return rq, 200, {'Content-Type': 'text/plain'}
    res = run_query(app.config['ENDPOINT'], rq)
    #else:
    #    url = data_base + path + '.n3'
    #    res = requests.get(url)
    graph = to_graph(res.content)
    this = graph.resource(uri)

    if fmt in ('html', 'xhtml'):
        return render_template(rtype + '.html',
                path=path, this=this, curies=graph.qname)
    else:
        headers = {'Content-Type': MIMETYPES.get(fmt) or 'text/plain'}
        fmt = {'rdf': 'xml', 'ttl': 'turtle'}.get(fmt) or fmt
        return graph.serialize(format=fmt), 200, headers
开发者ID:libris,项目名称:librislod,代码行数:30,代码来源:web.py


示例4: discussion_as_graph

    def discussion_as_graph(self, discussion_id):
        self.ensure_discussion_storage(None)
        from assembl.models import Discussion
        d_storage_name = self.discussion_storage_name()
        d_graph_iri = URIRef(self.discussion_graph_iri())
        v = get_virtuoso(self.session, d_storage_name)
        discussion_uri = URIRef(
            Discussion.uri_generic(discussion_id, self.local_uri()))
        subjects = list(v.query(
            """SELECT DISTINCT ?s WHERE {
            ?s assembl:in_conversation %s }""" % (discussion_uri.n3())))
        subjects.append([discussion_uri])
        # print len(subjects)
        cg = ConjunctiveGraph(identifier=d_graph_iri)
        for (s,) in subjects:
            # Absurdly slow. DISTINCT speeds up a lot, but I get numbers.
            for p, o in v.query(
                'SELECT ?p ?o WHERE { graph %s { %s ?p ?o }}' % (
                        d_graph_iri.n3(), s.n3())):
                    cg.add((s, p, o))

        for (s, o, g) in v.query(
                '''SELECT ?s ?o ?g WHERE {
                GRAPH ?g {?s catalyst:expressesIdea ?o } .
                ?o assembl:in_conversation %s }''' % (discussion_uri.n3())):
            cg.add((s, CATALYST.expressesIdea, o, g))

        # TODO: Add roles

        return cg
开发者ID:iilab,项目名称:assembl,代码行数:30,代码来源:virtuoso_mapping.py


示例5: discussion_as_graph

 def discussion_as_graph(self, discussion_id):
     from assembl.models import Discussion, AgentProfile
     local_uri = self.local_uri()
     discussion = Discussion.get(discussion_id)
     d_storage_name = self.discussion_storage_name()
     d_graph_iri = URIRef(self.discussion_graph_iri())
     v = get_virtuoso(self.session, d_storage_name)
     discussion_uri = URIRef(
         Discussion.uri_generic(discussion_id, local_uri))
     subjects = [s for (s,) in v.query(
         """SELECT DISTINCT ?s WHERE {
         ?s assembl:in_conversation %s }""" % (discussion_uri.n3()))]
     subjects.append(discussion_uri)
     participant_ids = list(discussion.get_participants(True))
     profiles = {URIRef(AgentProfile.uri_generic(id, local_uri))
                 for id in participant_ids}
     subjects.extend(profiles)
     # add pseudo-accounts
     subjects.extend((URIRef("%sAgentAccount/%d" % (local_uri, id))
                      for id in participant_ids))
     # print len(subjects)
     cg = ConjunctiveGraph(identifier=d_graph_iri)
     self.add_subject_data(v, cg, subjects)
     # add relationships of non-pseudo accounts
     for ((account, p, profile), g) in v.triples((None, SIOC.account_of, None)):
         if profile in profiles:
             cg.add((account, SIOC.account_of, profile, g))
             # Tempting: simplify with this.
             # cg.add((profile, FOAF.account, account, g))
     for (s, o, g) in v.query(
             '''SELECT ?s ?o ?g WHERE {
             GRAPH ?g {?s catalyst:expressesIdea ?o } .
             ?o assembl:in_conversation %s }''' % (discussion_uri.n3())):
         cg.add((s, CATALYST.expressesIdea, o, g))
     return cg
开发者ID:mydigilife,项目名称:assembl,代码行数:35,代码来源:virtuoso_mapping.py


示例6: detect_namespace

def detect_namespace(rdf):
    """Try to automatically detect the URI namespace of the vocabulary.

    Return namespace as URIRef.

    """

    # pick a concept
    conc = rdf.value(None, RDF.type, SKOS.Concept, any=True)
    if conc is None:
        logging.critical(
            "Namespace auto-detection failed. "
            "Set namespace using the --namespace option.")
        sys.exit(1)

    ln = localname(conc)
    ns = URIRef(conc.replace(ln, ''))
    if ns.strip() == '':
        logging.critical(
            "Namespace auto-detection failed. "
            "Set namespace using the --namespace option.")
        sys.exit(1)

    logging.info(
        "Namespace auto-detected to '%s' "
        "- you can override this with the --namespace option.", ns)
    return ns
开发者ID:NatLibFi,项目名称:Skosify,代码行数:27,代码来源:skosify.py


示例7: instance_view_jsonld

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,代码行数:26,代码来源:__init__.py


示例8: post

    def post(self):
        chan = URIRef(self.get_argument('chan'))
        sub = self.settings.currentSub()
        
        chanKey = Literal(chan.rsplit('/', 1)[1])
        old = sub.get_levels().get(chanKey, 0)

        sub.editLevel(chan, 0 if old else 1)
开发者ID:drewp,项目名称:light9,代码行数:8,代码来源:subcomposerweb.py


示例9: test_creation_with_unknown_ns

 def test_creation_with_unknown_ns(self):
     uri = 'http://localhost:8000/resource/aggregation/ton-smits-huis/454'
     predicate = RDFPredicate(uri)
     graph = Graph()
     graph.add((URIRef(uri), FOAF.name, Literal("sjoerd")))
     subject = list(graph.subjects())[0]
     uri_ref = URIRef(uri)
     assert uri_ref.n3() == "ns1:454"
     assert predicate is not None
     assert predicate.label is not None
开发者ID:delving,项目名称:nave,代码行数:10,代码来源:test_edm.py


示例10: get_service

def get_service():
    g = new_graph()
    me = URIRef(url_for('get_service', _external=True))
    g.add((me, RDF.type, SERVICE_TYPE))
    for db_resource in service_graph.subjects(RDF.type, PARTITION.Root):
        db_resource = URIRef(
            url_for('get_resource', rid=db_resource.replace(URI_PREFIX, ""), _external=True))
        g.add((me, CONTAINMENT_LINK, db_resource))
    response = make_response(g.serialize(format='turtle'))
    response.headers['Content-Type'] = 'text/turtle'
    return response
开发者ID:fserena,项目名称:rdf2rest,代码行数:11,代码来源:api.py


示例11: enterNewAnnotationMenu

    def enterNewAnnotationMenu(self):
        '''
        Interactive input for a new annotation
        '''
        
        self.printNewAnnotationMenu()

        i = 1
        for year in self.yearsAnnotations:
          print '{}) {}'.format(i,year["year"])
          i += 1
        print
            
        year = raw_input('Table to annotate: ')
        cell = raw_input('Cell to annotate: ')
        author = raw_input('Author: ')
        corrected = raw_input('Corrected value (leave blank if none): ')
        flag = raw_input('Flag: ')

        graphURI = URIRef(self.yearsAnnotations[int(year)-1]["uri"])
        d2sGraphURI = graphURI.replace("cedar-project.nl", "www.data2semantics.org")
        annoURI = URIRef(d2sGraphURI + '/NOORDBRABANT/' + cell)
        cellURI = annoURI.replace("annotations", "data")

        # Create the new annotation
        query = """
            PREFIX oa: <http://www.w3.org/ns/openannotation/core/>
            PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

            INSERT INTO GRAPH <""" + graphURI  + """>
            {
                <""" + annoURI  + """> a oa:Annotation;
                oa:annotated \"""" + str(datetime.datetime.now().strftime("%Y-%m-%d")) + """\"^^xsd:date;
                oa:annotator \"""" + author  + """\";
                oa:generated \"""" + str(datetime.datetime.now().strftime("%Y-%m-%d")) + """\"^^xsd:date;
                oa:generator <https://cedar-project.nl/tools/cedar-demo.py>;
                oa:hasBody [ rdf:value \"""" + corrected + ' ' + flag  + """\" ];
                oa:hasTarget <""" + cellURI  + """>;
                oa:modelVersion <http://www.openannotation.org/spec/core/20120509.html> .
            }
        """

        # query = "INSERT INTO GRAPH <http://cedar-project.nl/annotations/VT_1859_01_H1> {<http://a> rdf:type <http:b>}"

        print query

        self.sparql.setQuery(query)

        self.sparql.setReturnFormat(JSON)
        self.results = self.sparql.query().convert()
开发者ID:CEDAR-project,项目名称:MP2Demo,代码行数:50,代码来源:MP2Demo.py


示例12: check_valid_uri

 def check_valid_uri(self, uri):
     """ checks to see if a uri is valid """
     valid = False
     if isinstance(uri, str):
         uri_out = False
         try:
             uri_test = URIRef(uri)
             uri_out = uri_test.n3()
         except:
             # some sort of error thrown, so not valid
             valid = False
         if isinstance(uri_out, str):
             valid = True
     return valid
开发者ID:mfindeisen,项目名称:open-context-py,代码行数:14,代码来源:graph.py


示例13: tableView_objectValueForTableColumn_row_

    def tableView_objectValueForTableColumn_row_(self, tableView, tableColumn, row):
	id = tableColumn.identifier()
	uri = self.resources[row]
	if id=="uri":
	    base =self.context
	    base = base.split("#", 1)[0]
            uri = URIRef(uri.replace(base, "", 1)) # relativize
	    return uri
	elif id=="label":
	    return self.redfoot.label(uri, "")
	elif id=="comment":
	    return self.redfoot.comment(uri, "")
	else:
	    return ""
开发者ID:eikeon,项目名称:redfoot,代码行数:14,代码来源:EditorController.py


示例14: term

 def term(self, term, use_prefix=True):
     if isinstance(term, Namespace):
         term = URIRef(term)
     if term is None:
         return RDF.nil
     elif not hasattr(term, 'n3'):
         return self.term(Literal(term))
     elif use_prefix and isinstance(term, URIRef):
         return self.uri(term)
     elif isinstance(term, Literal):
         if term.datatype in (XSD.double, XSD.integer, XSD.float, XSD.boolean):
             return unicode(term).lower()
     elif isinstance(term, Namespace):
         return unicode(term)
     return term.n3()
开发者ID:nickswebsite,项目名称:sparqlquery,代码行数:15,代码来源:compiler.py


示例15: __init__

 def __init__(self, store, identifier=None, graph=None):
     if graph is not None:
         assert identifier is None
         np = store.node_pickler
         identifier = md5()
         s = list(graph.triples((None, None, None)))
         s.sort()
         for t in s:
             identifier.update("^".join((np.dumps(i) for i in t)))
         identifier = URIRef("data:%s" % identifier.hexdigest())
         super(GraphValue, self).__init__(store, identifier)
         for t in graph:
             store.add(t, context=self)
     else:
         super(GraphValue, self).__init__(store, identifier)
开发者ID:AuroraSkywalker,项目名称:watchdog,代码行数:15,代码来源:Graph.py


示例16: bulk_update

 def bulk_update(self, named_graph, graph, size, is_add=True):
     """
     Bulk adds or deletes. Triples are chunked into n size groups before
     sending to API. This prevents the API endpoint from timing out.
     """
     context = URIRef(named_graph)
     total = len(graph)
     if total > 0:
         for set_size, nt in self.nt_yielder(graph, size):
             if is_add is True:
                 logger.debug("Adding {} statements to <{}>.".format(set_size, named_graph))
                 self.update(u'INSERT DATA { GRAPH %s { %s } }' % (context.n3(), nt))
             else:
                 logger.debug("Removing {} statements from <{}>.".format(set_size, named_graph))
                 self.update(u'DELETE DATA { GRAPH %s { %s } }' % (context.n3(), nt))
     return total
开发者ID:senrabc,项目名称:vivo-rdflib-sparqlstore,代码行数:16,代码来源:bulk.py


示例17: get_idea_ids_showing_post

    def get_idea_ids_showing_post(cls, post_id):
        "Given a post, give the ID of the ideas that show this message"
        # This works because of a virtuoso bug...
        # where DISTINCT gives IDs instead of URIs.
        from .generic import Content
        discussion_storage = \
            AssemblQuadStorageManager.discussion_storage_name()

        post_uri = URIRef(Content.uri_generic(
            post_id, AssemblQuadStorageManager.local_uri()))
        return [int(id) for (id,) in cls.default_db.execute(SparqlClause(
            '''select distinct ?idea where {
                %s sioc:reply_of* ?post .
                ?post assembl:postLinkedToIdea ?ideaP .
                ?idea idea:includes* ?ideaP  }''' % (post_uri.n3(),),
            quad_storage=discussion_storage.n3()))]
开发者ID:rmoorman,项目名称:assembl,代码行数:16,代码来源:idea.py


示例18: __init__

 def __init__(self, parent, identifier=None, meta=None):
     self.parent = parent
     if identifier is None:
         identifier = BNode()
     self.identifier = URIRef(identifier)
     self.meta = MetaData(self, meta)
     self.meta.generate()
开发者ID:backgroundcheck,项目名称:jsongraph,代码行数:7,代码来源:context.py


示例19: DOI

class DOI(DOIMetadata):
    """find and download a pdf for the doi given
    >>> DOI('10.1016/0166-218X(92)00170-Q')
    """
    headers = generic_headers
    headers['Host'] = 'gen.lib.rus.ec'
    headers['Referer'] = 'http://gen.lib.rus.ec/scimag/'
    
    url = 'http://gen.lib.rus.ec/scimag/?s={}&journalid=&v=&i=&p=&redirect=1'
    
    def __init__(self, doi, *args, **kwargs):
        super().__init__(doi, *args, **kwargs)
        self.url = URIRef(self.url.format(self.doi))
        
        r = requests.get(self.url, headers=self.headers)
        r.raise_for_status()
        
        self.links = re.compile(r'a href="([^"]+pdf)"').findall(r.text)
        link, *links = self.links
        r = requests.get(link, stream=True)
        
        self.filename = Literal('.'.join((doi.replace('/','_'), 'pdf')))
        with open(self.filename, 'wb') as fd:
            for chunk in r.iter_content(1024*10):
                fd.write(chunk)
        
        self.path = URIRef(urljoin('file:', pjoin(os.getcwd(), self.filename)))
        self.graph.add((self.path, URIRef('http://purl.org/dc/terms/identifier'), self.doi))
        self.graph.commit()
开发者ID:douglas-larocca,项目名称:articles,代码行数:29,代码来源:articles.py


示例20: canvas_and_images_graph

def canvas_and_images_graph(graph, canvas_uri):
    canvas_uri = URIRef(canvas_uri)

    canvas_graph = Graph()
    canvas_graph += graph.triples((canvas_uri, None, None))

    qres = graph.query("""SELECT ?image_anno ?image WHERE {
        ?image_anno a oa:Annotation .
        ?image_anno oa:hasTarget %s .
        ?image_anno oa:hasBody ?image .
        ?image a ?type .
        FILTER(?type = dcmitype:Image || ?type = dms:Image || ?type = dms:ImageChoice) .
    }""" % (canvas_uri.n3()), initNs=ns)

    for image_anno, image in qres:
        canvas_graph += graph.triples_choices(([image_anno, image], None, None))

    return canvas_graph
开发者ID:bobclewell,项目名称:DM,代码行数:18,代码来源:canvases.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python Graph.ConjunctiveGraph类代码示例发布时间:2022-05-26
下一篇:
Python rdflib.Graph类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap