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


Python ConjunctiveGraph.parse方法代码示例

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


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

示例1: _user_graph

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
 def _user_graph(self, uri):
     userGraph = Graph()
     try:
         userGraph.parse(uri)
     except Exception, e:
         u = "http://www.w3.org/2007/08/pyRdfa/extract?space-preserve=true&uri=" + uri
         userGraph.parse(u, identifier=uri)
开发者ID:sylvar,项目名称:supybot-plugins,代码行数:9,代码来源:plugin.py

示例2: partsites

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
    def partsites(self):
        context = aq_inner(self.context)

        _partsiteType = _mcltype.FundedSite

        # title
        _title = _terms.title
        # description
        _description = _terms.description

        # Temporary rdf read
        rdfDataSource = "https://edrn-dev.jpl.nasa.gov/ksdb/publishrdf/?rdftype=fundedsite"
        graph = ConjunctiveGraph()
        graph.parse(URLInputSource(rdfDataSource))
        statements = _parseRDF(graph)

        partsites = []
        for uri, i in statements.items():
            partsite = dict(url=uri, title="", description="")
            if _title in i:
                partsite["title"] = unicode(i[_title][0])
            if _description in i:
                partsite["description"] = strip_tags(unicode(i[_description][0]))

            partsites.append(partsite)

        return partsites
开发者ID:MCLConsortium,项目名称:jpl.mcl.protocol,代码行数:29,代码来源:views.py

示例3: FOAF

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
class FOAF(callbacks.Privmsg):

    DATAFILE = "/var/www/rc98.net/zoia.rdf"

    def __init__(self, irc):
        self.g = Graph()
        #      self.g.parse('http://rc98.net/zoia.rdf')
        self.g.parse(self.DATAFILE, format="xml")
        self.uri = rdflib.URIRef("http://www.code4lib.org/id/zoia")
        self.FOAF = Namespace("http://xmlns.com/foaf/0.1/")
        super(callbacks.Plugin, self).__init__(irc)

    def _uri_of_user(self, nick):
        result = self.g.query(
            """
          PREFIX foaf: <http://xmlns.com/foaf/0.1/> 
          SELECT ?uri WHERE 
          {<http://www.code4lib.org/id/zoia> foaf:knows ?uri . ?uri foaf:nick ?nick .}
          """,
            initBindings={"nick": nick},
        )
        if len(result) > 0:
            userURI = list(result)[0][0]
            return userURI
        else:
            return None

    def _user_graph(self, uri):
        userGraph = Graph()
        try:
            userGraph.parse(uri)
        except Exception, e:
            u = "http://www.w3.org/2007/08/pyRdfa/extract?space-preserve=true&uri=" + uri
            userGraph.parse(u, identifier=uri)
        return userGraph
开发者ID:sylvar,项目名称:supybot-plugins,代码行数:37,代码来源:plugin.py

示例4: serialize_demo

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
def serialize_demo():
    try:
        store = ConjunctiveGraph()
        store.parse(FILE, format='xml')
        print store.serialize(format='xml')
    except OSError:
        print "Cannot read file '%s'" % FILE
开发者ID:AndrewHu2013,项目名称:KAT,代码行数:9,代码来源:rdfVisualizer.py

示例5: projects

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
    def projects(self):
        context = aq_inner(self.context)

        _projectType = _mcltype.Project

        # title
        _title = _terms.title
        # abbriviation
        _abbrName = _schema.abbreviatedName
        # description
        _description = _terms.description

        # Temporary rdf read
        rdfDataSource = "https://edrn-dev.jpl.nasa.gov/ksdb/publishrdf/?rdftype=project"
        graph = ConjunctiveGraph()
        graph.parse(URLInputSource(rdfDataSource))
        statements = _parseRDF(graph)

        projects = []
        for uri, i in statements.items():
            project = dict(url=uri, title="", abbrName="", description="")
            if _title in i:
                project["title"] = unicode(i[_title][0])
            if _abbrName in i:
                project["abbrName"] = unicode(i[_abbrName][0])
            if _description in i:
                project["description"] = strip_tags(unicode(i[_description][0]))

            projects.append(project)

        return projects
开发者ID:MCLConsortium,项目名称:jpl.mcl.protocol,代码行数:33,代码来源:views.py

示例6: change_status

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
def change_status(vocabprefix, uri, predicate, message, action):
    if not action in ['add', 'remove']:
        return False
    vocab_uri = URIRef(uri)
    vocabdir = os.path.join(ag.vocabulariesdir, vocabprefix)
    vocabstatusfile = os.path.join(vocabdir, "status.rdf")
    if not os.path.isfile(vocabstatusfile):
        return False
    graph = Graph()
    graph.parse(vocabstatusfile)
    predicate = predicate.split(':')
    ns = predicate[0]
    term = predicate[1]
    if message and (message.startswith('http://') or message.startswith('file://')):
        message = URIRef(message)
    elif message:
        message = Literal(message)
    if action == 'add':
        for prefix, url in namespaces.iteritems():
            graph.bind(prefix, URIRef(url))
        graph.add((vocab_uri, namespaces[ns][term], message))
    elif action == 'remove':
        graph.remove((vocab_uri, namespaces[ns][term], message))
     
    rdf_str = None
    rdf_str = graph.serialize()
    f = codecs.open(vocabstatusfile, 'w', 'utf-8')
    f.write(rdf_str)
    f.close()
    return True
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:32,代码来源:rdf_helper.py

示例7: update_mediator

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
def update_mediator(params):
    #Write user metadata and save the rdf file
    if not ('username' in params and params['username']):
        return False
    det = get_mediator_details(params['username'])
    graph = Graph()
    graph.parse(os.path.join(ag.mediatorsdir, '%s.rdf'%params['username']))
    for prefix, url in namespaces.iteritems():
        graph.bind(prefix, URIRef(url))
    uri = URIRef(det['uri'])
    if 'firstname' in params and params['firstname']:
        graph.remove((uri, namespaces['foaf']['firstName'], None))
        graph.add((uri, namespaces['foaf']['firstName'], Literal(params['firstname'])))
    if 'lastname' in params and params['lastname']:
        graph.remove((uri, namespaces['foaf']['lastName'], None))
        graph.add((uri, namespaces['foaf']['lastName'], Literal(params['lastname'])))
    if 'email' in params and params['email']:
        graph.remove((uri, namespaces['foaf']['mbox'], None))
        graph.add((uri, namespaces['foaf']['mbox'], Literal(params['email'])))
    if 'title' in params and params['title']:
        graph.remove((uri, namespaces['foaf']['title'], None))
        graph.add((uri, namespaces['foaf']['title'], Literal(params['title'])))
    if 'department' in params and params['department']:
        graph.remove((uri, namespaces['dcterms']['isPartOf'], None))
        department = params['department'].split(';')
        for d in department:
            graph.add((uri, namespaces['dcterms']['isPartOf'], Literal(d.strip())))
    rdf_str = None
    rdf_str = graph.serialize()
    f = codecs.open(os.path.join(ag.mediatorsdir, '%s.rdf'%params['username']), 'w', 'utf-8')
    f.write(rdf_str)
    f.close()
    return True
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:35,代码来源:rdf_helper.py

示例8: add_mediator

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
def add_mediator(params):
    #Write user metadata and save the rdf file
    graph = Graph()
    for prefix, url in namespaces.iteritems():
        graph.bind(prefix, URIRef(url))
    uri = URIRef("http://vocab.ox.ac.uk/owner/uuid:%s"%uuid.uuid4())
    graph.add((uri, namespaces['foaf']['firstName'], Literal(params['firstname'])))
    graph.add((uri, namespaces['foaf']['lastName'], Literal(params['lastname'])))
    graph.add((uri, namespaces['foaf']['mbox'], Literal(params['email'])))
    graph.add((uri, namespaces['foaf']['account'], Literal(params['username'])))
    if 'title' in params and params['title']:
        graph.add((uri, namespaces['foaf']['title'], Literal(params['title'])))
    if 'department' in params and params['department']:
        department = params['department'].split(';')
        for d in department:
            graph.add((uri, namespaces['dcterms']['isPartOf'], Literal(d.strip())))
    rdf_str = None
    rdf_str = graph.serialize()
    f = codecs.open(os.path.join(ag.mediatorsdir, '%s.rdf'%params['username']), 'w', 'utf-8')
    f.write(rdf_str)
    f.close()
    graph2 = Graph()
    graph2.parse(ag.mediatorslist)
    for prefix, url in namespaces.iteritems():
        graph2.bind(prefix, URIRef(url))
    graph2.add((uri, namespaces['foaf']['account'], Literal(params['username'])))
    rdf_str = None
    rdf_str = graph2.serialize()
    f = codecs.open(ag.mediatorslist, 'w', 'utf-8')
    f.write(rdf_str)
    f.close()
    return True
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:34,代码来源:rdf_helper.py

示例9: initialize

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
def initialize(config_file):
    print '[%s] Initializing...' % strftime("%a, %d %b %Y %H:%M:%S", localtime())
    sys.stdout.flush()
    
    config = __import__(config_file)
    
    try:
        g = ConjunctiveGraph(config.graph_store, config.graph_identifier)
        g.open(config.db_configstring, create=True)
        if config.input_file != None:
            print '[%s] Parsing %s...' % (strftime("%a, %d %b %Y %H:%M:%S", localtime()), config.input_file)
            sys.stdout.flush()
            g.parse(config.input_file, format=config.input_format)
            g.commit()
        else:
            dir_list = os.listdir(config.input_dir)
            for file_name in dir_list:
                print '[%s] Parsing %s...' % (strftime("%a, %d %b %Y %H:%M:%S", localtime()) ,file_name)
                sys.stdout.flush()
                g.parse(config.input_dir + '/' + file_name, format=config.input_format)
                g.commit()
    except Exception as e:
        traceback.print_exc()
        print e 
        print '"%s" not found, or incorrect RDF serialization.' % config.input_file
        sys.stdout.flush()
        exit(-1)
    return g, config
开发者ID:memaldi,项目名称:rdf2subdue,代码行数:30,代码来源:rdf2subdue.py

示例10: get_rdf

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
def get_rdf():
    rdf = ConjunctiveGraph()
    for key in COUNTRIES.keys():
        print "parsing %s" % COUNTRIES[key]
        rdf.parse(COUNTRIES[key])
    print "serialize"
    rdf.serialize("countries.rdf")
开发者ID:apassant,项目名称:motools,代码行数:9,代码来源:geonames_rdf.py

示例11: ConvertToRDFN3

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

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

示例12: _test_serializer

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
def _test_serializer(inputpath, expectedpath, context, serpar):
    test_tree, test_graph = _load_test_data(inputpath, expectedpath, context)

    if isinstance(test_tree, ConjunctiveGraph):
        expected = test_tree.serialize(format="json-ld")
    else:
        expected = _to_json(_to_ordered(test_tree))

    if test_graph is not None:
        # toRdf, expected are nquads
        result_tree = to_tree(test_graph, context_data=context)
        result = _to_json(_to_ordered(result_tree))

    elif inputpath.startswith('fromRdf'):
        # fromRdf, expected in json-ld
        g = ConjunctiveGraph()
        data = open(p.join(test_dir, inputpath), 'rb').read()
        g.parse(data=data, format="nquads", context=context)
        result = g.serialize(format="json-ld", base=context)

    else:
        # json
        f = open(p.join(test_dir, inputpath), 'rb')
        result = json.load(f)[0]
        f.close()

    if isinstance(result, ConjunctiveGraph):
        assert isomorphic(result, expected), \
            "Expected graph of %s:\n%s\nGot graph of %s:\n %s" % (
                expected.serialize(format='n3'),
                result.serialize(format='n3'))
    else:
        assert jsonld_compare(expected, result) == True, \
                "Expected JSON:\n%s\nGot:\n%s" % (expected, result)
开发者ID:junchang,项目名称:rdflib-jsonld,代码行数:36,代码来源:test_testsuite.py

示例13: fusion

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
def fusion(ontologies, output):
	global mode

	# 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#")

	# Final graph creation
	gMerge = ConjunctiveGraph()

	myPrint("Beginning additions...\n\n")
	for ontology in ontologies:
		gAdd = ConjunctiveGraph()
		if mode == 2 or mode == 3:
			myPrint("\tParsing ontology "+ontology+"...\n")
		gAdd.parse(ontology, format=guess_format(ontology))
		if mode == 2 or mode == 3:
			myPrint("\tAdding ontology "+ontology+", "+str(len(gAdd))+ " triples...\n")
		gMerge = gMerge + gAdd
		if mode == 2 or mode == 3:
			myPrint("\tOntology "+ontology+" added !\n")
			myPrint("\tNew size of merged ontology : "+str(len(gMerge))+" triples\n\n")

	myPrint("Additions complete !\n")
	myPrint("Final size of merged ontology : "+str(len(gMerge))+" triples\n\n")

	myPrint("Saving the ontology in turtle format...\n")
	# Saving the merged ontology in turtle
	gMerge.serialize(output, format="turtle")
	myPrint("Saving done !\n\n")
开发者ID:LilyOfTheWest,项目名称:OntologyTool,代码行数:36,代码来源:fusion_tool.py

示例14: get_graph

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
    def get_graph(self, with_mappings=False, include_mapping_target=False, acceptance=False, target_uri=None):
        """Get Graph instance of this EDMRecord.

        :param target_uri: target_uri if you want a sub-selection of the whole graph
        :param acceptance: if the acceptance data should be listed
        :param include_mapping_target: Boolean also include the mapping target triples in graph
        :param with_mappings: Boolean integrate the ProxyMapping into the graph
        """
        rdf_string = self.source_rdf
        if acceptance and self.acceptance_rdf:
            rdf_string = self.acceptance_rdf

        graph = ConjunctiveGraph(identifier=self.named_graph)
        graph.namespace_manager = namespace_manager
        graph.parse(data=rdf_string, format='nt')
        if with_mappings:
            proxy_resources, graph = ProxyResource.update_proxy_resource_uris(self.dataset, graph)
            self.proxy_resources.add(*proxy_resources)
            for proxy_resource in proxy_resources:
                graph = graph + proxy_resource.to_graph(include_mapping_target=include_mapping_target)
        if target_uri and not target_uri.endswith("/about") and target_uri != self.document_uri:
            g = Graph(identifier=URIRef(self.named_graph))
            subject = URIRef(target_uri)
            for p, o in graph.predicate_objects(subject=subject):
                g.add((subject, p, o))
            graph = g
        return graph
开发者ID:delving,项目名称:nave,代码行数:29,代码来源:models.py

示例15: construct

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import parse [as 别名]
 def construct(self, strOrTriple, initBindings={}, initNs={}):
     """
     Executes a SPARQL Construct
     :param strOrTriple: can be either
     
       * a string in which case it it considered a CONSTRUCT query
       * a triple in which case it acts as the rdflib `triples((s,p,o))`
     
     :param initBindings:  A mapping from a Variable to an RDFLib term (used as initial bindings for SPARQL query)
     :param initNs:  A mapping from a namespace prefix to a namespace
     
     :returns: an instance of rdflib.ConjuctiveGraph('IOMemory')
     """
     if isinstance(strOrTriple, str):
         query = strOrTriple
         if initNs:
             prefixes = ''.join(["prefix %s: <%s>\n"%(p,n) for p,n in initNs.items()])
             query = prefixes + query
     else:
         s,p,o = strOrTriple
         t='%s %s %s'%((s and s.n3() or '?s'),(p and p.n3() or '?p'),(o and o.n3() or '?o'))
         query='construct {%s} where {%s}'%(t,t)
     query = dict(query=query)
     
     url = self.url+"?"+urlencode(query)
     req = Request(url)
     req.add_header('Accept','application/rdf+xml')
     log.debug("Request url: %s\n  with headers: %s" % (req.get_full_url(), req.header_items()))        
     subgraph = ConjunctiveGraph('IOMemory')
     subgraph.parse(urlopen(req))
     return subgraph
开发者ID:openvest,项目名称:RDFAlchemy,代码行数:33,代码来源:__init__.py


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