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


Python Graph.close方法代码示例

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


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

示例1: clear

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
def clear():
	# Configurations
	config = ConfigParser()
	config.read('config.ini')

	endpoint_uri = config['Mandatory']['endpointURI']
	graph_uri = config['Mandatory']['graphURI']

	clean_graph_query = "CLEAR GRAPH <"+graph_uri+">"

	# Set up endpoint and access to triple store
	sparql = SPARQLWrapper(endpoint_uri)
	sparql.setReturnFormat(JSON)
	sparql.setMethod(POST)
	store = SPARQLUpdateStore(endpoint_uri, endpoint_uri)

	# Specify the (named) graph we're working with
	sparql.addDefaultGraph(graph_uri)

	# Create an in memory graph
	g = Graph(store, identifier=graph_uri)

	# Cleanup the existing triples
	sparql.setQuery(clean_graph_query)
	sparql.query().convert()

	# Cleanup the graph instance
	g.close()
开发者ID:catalogue-of-services-isa,项目名称:cpsv-ap_harvester,代码行数:30,代码来源:clear_graph.py

示例2: RDFStorage

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
class RDFStorage(object):
  name = DEFAULT_DB
  def __init__(self):
    super(RDFStorage, self).__init__()
    store = plugin.get("SQLAlchemy", Store)(identifier=IDENTIFIER)
    self.graph = Graph(store, identifier=IDENTIFIER)

  def __del__(self):
    self.close()

  def open(self, dbName = DEFAULT_DB, create = True):
    if not dbName: return -1
    self.name = dbName
    if not dbName.startswith("sqlite:///"):
      dbName = "sqlite:///" + dbName
    return self.graph.open(dbName, create)

  def _delete_old(self, fName):
    if os.path.exists(fName):
      os.remove(fName)

  def close(self):
    self.graph.close()

  def storeData(self, data, format = "n3"):
    self._delete_old(self.name)
    self.open(self.name)
    self.graph.parse(data = data, format = format)

  def query(self, qString):
    self.open(self.name)
    return self.graph.query(qString)
开发者ID:BloodyD,项目名称:rdfStore,代码行数:34,代码来源:__init__.py

示例3: Test

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
class Test(unittest.TestCase):

    def setUp(self):
        self.g = Graph()
        self.g.parse("../graph/for_test_graph.ttl", format="turtle")
        self.mashup = "http://www.programmableweb.com/mashup/fast-quick-online-translator"
        self.query = exp.compose_query(self.g, self.mashup)
        self.candidate_set = exp.candidate_set(self.query, self.g)

    def tearDown(self):
        self.g.close()

    def test_query_creation(self):
        self.assertEqual(len(self.query["services"]), 2)
        self.assertEqual(len(self.query["categories"]), 2)
        self.assertEqual(self.query["reg_date"], datetime.date(2010, 4, 26))

    def test_union_of_two_lists(self):
        A = ["A", "B", "C"]
        B = ["C", "B"]
        self.assertEqual(exp.union_of_two_lists(A, B), ["A", "B", "C"])

    def test_score_computation(self):
        services = ["http://www.programmableweb.com/api/lingo24-translation"]
        score = exp.score(self.g, services, self.query["categories"], 1, 1, 1)
        self.assertEqual(sum(score), 0.75)

    def test_candidate_set_creation(self):
        self.assertEqual(len(self.candidate_set), 9)

    def test_recommendation_algorithm(self):
        expected_recommendation = [rdflib.term.URIRef('http://www.programmableweb.com/api/google-ajax-language'),
                                   rdflib.term.URIRef('http://www.programmableweb.com/api/google-translate')]
        self.assertEqual(exp.Greedy(self.g, self.query["categories"],
                                    self.candidate_set, len(self.query["services"]), 1, 1, 1)[0], expected_recommendation)
开发者ID:omelkova,项目名称:pw_crawler,代码行数:37,代码来源:test_experiment.py

示例4: CoreSQLiteStoreTestCase

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
class CoreSQLiteStoreTestCase(unittest.TestCase):
    """
    Test case for SQLite core.
    """

    store = "SQLite"
    path = None
    storetest = True

    def setUp(self):
        self.graph = Graph(store=self.store)
        fp, self.path = tempfile.mkstemp(suffix=".sqlite")
        self.graph.open(self.path, create=True)

    def tearDown(self):
        # TODO: delete a_tmp_dir
        self.graph.close()
        del self.graph
        if hasattr(self, "path") and self.path is not None:
            if os.path.exists(self.path):
                if os.path.isdir(self.path):
                    for f in os.listdir(self.path):
                        os.unlink(self.path + "/" + f)
                    os.rmdir(self.path)
                elif len(self.path.split(":")) == 1:
                    os.unlink(self.path)
                else:
                    os.remove(self.path)

    def test_escape_quoting(self):
        test_string = "This's a Literal!!"
        self.graph.add((URIRef("http://example.org/foo"), RDFS.label, Literal(test_string, datatype=XSD.string)))
        self.graph.commit()
        assert b("This's a Literal!!") in self.graph.serialize(format="xml")
开发者ID:RDFLib,项目名称:rdflib-sqlite,代码行数:36,代码来源:test_core_sqlite.py

示例5: DeepGraphStore

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
class DeepGraphStore():
    store_name = settings.DEEPGRAPHS_DEFAULT_STORAGE

    def __init__(self, create=True):
        self.create = create
        self.path = "databases/" + random_file_generating()

    def setUp(self):
        self.graph = Graph(store=self.store_name)
        self.graph.open(self.path, create=self.create)

        if self.create:
            self.graph.parse("http://njh.me/foaf.rdf", format='xml')
            self.graph.commit()

    def open(self, path):
        self.graph = Graph(self.store_name).open(path, False)
        return self.graph.__len__

    def query(self, sparql_query):
        return self.graph.query(sparql_query)

    def parse(self, path_to_file_):
        self.graph.parse(path_to_file_)

    def load(self, triples):
        self.graph.load(triples)

    def close(self):
        self.graph.close()

    def size(self):
        size = self.graph.__len__
        self.close()
        return size
开发者ID:deepgraphs,项目名称:dgraphdb,代码行数:37,代码来源:dgraphdbstore.py

示例6: rdf

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
    def rdf(urlrdf, f):
        input = Graph()
        input.open("store2", create=True)
        input.parse(urlrdf, format=f)
        
        for s, p, o in input:
            g.add((s, p, o))

        input.close()
开发者ID:catalogue-of-services-isa,项目名称:cpsv-ap_harvester,代码行数:11,代码来源:harvester.py

示例7: StoreTestCase

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
class StoreTestCase(unittest.TestCase):
    """
    Test case for testing store performance... probably should be
    something other than a unit test... but for now we'll add it as a
    unit test.
    """
    store = 'IOMemory'
    path = None
    storetest = True
    performancetest = True

    def setUp(self):
        self.gcold = gc.isenabled()
        gc.collect()
        gc.disable()

        self.graph = Graph(store=self.store)
        from test_postgresql import configString
        from rdflib_postgresql.PostgreSQL import PostgreSQL
        path = configString
        PostgreSQL().destroy(path)
        self.path = path
        self.graph.open(self.path, create=True)
        self.input = Graph()

    def tearDown(self):
        self.graph.close()
        if self.gcold:
            gc.enable()
        # TODO: delete a_tmp_dir
        self.graph.close()

    def testTime(self):
        # number = 1
        print('"%s": [' % self.store)
        for i in ['500triples', '1ktriples', '2ktriples',
                  '3ktriples', '5ktriples', '10ktriples',
                  '25ktriples']:
            inputloc = os.getcwd() + '/test/sp2b/%s.n3' % i
            res = self._testInput(inputloc)
            print("%s," % res.strip())
        print("],")

    def _testInput(self, inputloc):
        number = 1
        store = self.graph
        self.input.parse(location=inputloc, format="n3")

        def add_from_input():
            for t in self.input:
                store.add(t)
        it = itertools.repeat(None, number)
        t0 = time()
        for _i in it:
            add_from_input()
        t1 = time()
        return "%.3g " % (t1 - t0)
开发者ID:RDFLib,项目名称:rdflib-postgresql,代码行数:59,代码来源:test_store_performance.py

示例8: SPARQLStoreDBPediaTestCase

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
class SPARQLStoreDBPediaTestCase(unittest.TestCase):
    store_name = 'SPARQLStore'
    path = "http://dbpedia.org/sparql"
    storetest = True
    create = False

    def setUp(self):
        self.graph = Graph(store="SPARQLStore")
        self.graph.open(self.path, create=self.create)
        ns = list(self.graph.namespaces())
        assert len(ns) > 0, ns

    def tearDown(self):
        self.graph.close()

    def test_Query(self):
        query = "select distinct ?Concept where {[] a ?Concept} LIMIT 1"
        res = self.graph.query(query, initNs={})
        for i in res:
            assert type(i[0]) == URIRef, i[0].n3()

    def test_initNs(self):
        query = """\
        SELECT ?label WHERE
            { ?s a xyzzy:Concept ; xyzzy:prefLabel ?label . } LIMIT 10
        """
        res = self.graph.query(
            query,
            initNs={"xyzzy": "http://www.w3.org/2004/02/skos/core#"})
        for i in res:
            assert type(i[0]) == Literal, i[0].n3()

    def test_noinitNs(self):
        query = """\
        SELECT ?label WHERE
            { ?s a xyzzy:Concept ; xyzzy:prefLabel ?label . } LIMIT 10
        """
        self.assertRaises(
            SPARQLWrapper.Wrapper.QueryBadFormed,
            self.graph.query,
            query)

    def test_query_with_added_prolog(self):
        prologue = """\
        PREFIX xyzzy: <http://www.w3.org/2004/02/skos/core#>
        """
        query = """\
        SELECT ?label WHERE
            { ?s a xyzzy:Concept ; xyzzy:prefLabel ?label . } LIMIT 10
        """
        res = self.graph.query(prologue + query)
        for i in res:
            assert type(i[0]) == Literal, i[0].n3()
开发者ID:Dataliberate,项目名称:rdflib,代码行数:55,代码来源:test_sparqlstore.py

示例9: investigate_len_issue

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
def investigate_len_issue():
    import shutil, commands
    store = plugin.get('SQLAlchemy', Store)(
        identifier=URIRef("rdflib_test"),
        configuration=Literal("sqlite:///%(here)s/development.sqlite" % {
                                                        "here": os.getcwd()}))
    g0 = Graph('Sleepycat')
    g0.open('/tmp/foo', create=True)
    print("Len g0 on opening: %s\n" % len(g0))
    g1 = Graph(store)
    print("Len g1 on opening: %s\n" % len(g1))
    statementId = BNode()
    print("Adding %s\n\t%s\n\t%s\n" % (statementId, RDF.type, RDF.Statement))
    g0.add((statementId, RDF.type, RDF.Statement))
    g1.add((statementId, RDF.type, RDF.Statement))
    print("Adding %s\n\t%s\n\t%s\n" % (statementId, RDF.subject,
           URIRef(u'http://rdflib.net/store/ConjunctiveGraph')))
    g0.add((statementId, RDF.subject,
           URIRef(u'http://rdflib.net/store/ConjunctiveGraph')))
    g1.add((statementId, RDF.subject,
           URIRef(u'http://rdflib.net/store/ConjunctiveGraph')))
    print("Adding %s\n\t%s\n\t%s\n" % (statementId, RDF.predicate, RDFS.label))
    g0.add((statementId, RDF.predicate, RDFS.label))
    g1.add((statementId, RDF.predicate, RDFS.label))
    print("Adding %s\n\t%s\n\t%s\n" % (
        statementId, RDF.object, Literal("Conjunctive Graph")))
    g0.add((statementId, RDF.object, Literal("Conjunctive Graph")))
    print("Len g0 after adding 4 triples %s\n" % len(g0))
    g1.add((statementId, RDF.object, Literal("Conjunctive Graph")))
    print("Len g1 after adding 4 triples %s\n" % len(g1))
    print(g0.serialize(format="nt") + "\n")
    for s, p, o in g0:
        print("s = %s\n\tp = %s\n\to = %s\n" % (
            repr(s), repr(p), repr(o)))
    print(g1.serialize(format="nt") + "\n")
    for s, p, o in g1:
        print("s = %s\n\tp = %s\n\to = %s\n" % (
            repr(s), repr(p), repr(o)))
    commands.getoutput('cp development.sqlite devcopy.sqlite')
    print("Removing %s\n\t%s\n\t%s\n" % (statementId, RDF.type, RDF.Statement))
    g0.remove((statementId, RDF.type, RDF.Statement))
    print("Len g0 after removal %s\n" % len(g0))
    g1.remove((statementId, RDF.type, RDF.Statement))
    print("Len g1 after removal %s\n" % len(g1))
    print(g0.serialize(format="nt") + "\n")
    print(g1.serialize(format="nt") + "\n")
    g0.close()
    shutil.rmtree('/tmp/foo')
    g1.close()
    os.unlink("%(here)s/development.sqlite" % {"here": os.getcwd()})
开发者ID:IRI-Research,项目名称:rdflib-sqlalchemy,代码行数:52,代码来源:test.py

示例10: removeFromGraph

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
def removeFromGraph(timestamp, graphURI = "http://example.com/g1", db_conf={"dbname" : "postgres", "user" : "postgres", "password" : "admin" }):
    configString = ("dbname=postgres user=waccess password=write")
    #configString = ("dbname=" + db_conf['dbname'] + "user="+ db_conf['user'] + " password=" + db_conf['password'])
    graph = Graph('PostgreSQL', identifier=URIRef(graphURI))
    graph.open(configString, create=False)
    results = graph.query(queries.getEvents(timestamp))

    print len(results)
    for result in results:
        for node in result:
            graph.remove((node, None, None))

    # Commit and close the graph
    graph.commit()
    graph.close()
开发者ID:nikha1,项目名称:nyc-taxi,代码行数:17,代码来源:postgresInterface.py

示例11: PersonPipeline

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
class PersonPipeline(object):

    def __init__(self):
        self.base = 'http://example.com/person/'
        self.count = 0
        self.repo = Graph(store='default')
        self.repo.bind('foaf', FOAF)

    def process_item(self, item, spider):
        self.count += 1
        resource = URIRef(self.base + str(self.count))
        self.repo.add((resource, RDF.type, FOAF.Person))
        self.repo.add((resource, FOAF.firstName, Literal(item['firstName'], lang='ru')))
        self.repo.add((resource, FOAF.lastName, Literal(item['lastName'], lang='ru')))

    def close_spider(self, spider):
        f = open('dump.ttl', 'w')
        self.repo.serialize(f, format='turtle')
        self.repo.close()
开发者ID:ailabitmo,项目名称:semweb-course,代码行数:21,代码来源:pipelines.py

示例12: StreetRepo

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
class StreetRepo(object):
  def __init__(self):
    self.namespace = Namespace('http://schema.org/')
    self.base = 'http://ifmo.com/address/'
    self.count = 0
    self.repo = Graph(store='default')
    self.repo.bind('schema', self.namespace)

  def process_street(self, item):
    self.count += 1
    resource = URIRef(self.base + str(self.count))
    geo = URIRef(self.base + str(self.count) + '/geo')
    address = URIRef(self.base + str(self.count) + '/address')

    self.repo.add((resource, RDF.type, self.namespace.Place))
    self.repo.add((resource, self.namespace.GeoCoordinates, geo))
    self.repo.add((resource, self.namespace.PostalAddress, address))

    self.repo.add((geo, RDF.type, self.namespace.GeoCoordinates))
    self.repo.add((address, RDF.type, self.namespace.PostalAddress))

    self.repo.add((address, self.namespace.postalCode, Literal(item['postindex'], lang='en')))
    self.repo.add((address, self.namespace.addressRegion, Literal(item['region'], lang='ru')))
    self.repo.add((address, self.namespace.addressLocality, Literal(item['city'], lang='ru')))
    self.repo.add((address, self.namespace.streetAddress, Literal(item['street'], lang='ru')))

    request = "http://geocode-maps.yandex.ru/1.x/?geocode=Россия, " + item['region'] + " " + item['city'] + " " + item['street']
    geo_root = ET.parse(urllib.urlopen(request)).getroot()
    pos = geo_root.findall('.//{http://www.opengis.net/gml}pos')
    if(len(pos) > 0):
      coords = pos[0].text.split(" ")
      lat = coords[1]
      lon = coords[0]
      self.repo.add((geo, self.namespace.latitude, Literal(lat, lang='en')))
      self.repo.add((geo, self.namespace.longitude, Literal(lon, lang='en')))
    print self.count


  def close(self):
    f = open('open-street.ttl','w')
    self.repo.serialize(f, format='turtle')
    self.repo.close()
开发者ID:KorixD,项目名称:PostIndexes,代码行数:44,代码来源:open-street.py

示例13: BenchableGraph

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
class BenchableGraph(object):
    """
    Provides a convenient way to use a graph for benchmarks.

    """
    def __init__(self, store, graph_id, store_config, graph_create=False):
        """
        :param str store: Type of store to use.
        :param str graph_id: The graph identifier.
        :param store_config: Configuration to open the store.
        :type store_config: str or tuple
        :param bool graph_create: True to create the graph upon connecting.
        """
        self.graph = Graph(store=store, identifier=graph_id)
        self._graph_id = graph_id
        self._store_config = store_config
        self._graph_create = graph_create

    def connect(self):
        """Connect to the store.

        .. note::

            For some configurations, RDFlib will postpone the actual connection to
            the store until needed (when doing a graph.query() or graph.add()).

            This behaviour comes from RDFbib implementation of graph.open().
        """
        return self.graph.open(configuration=self._store_config, create=self._graph_create)

    def close(self, commit_pending_transaction=True):
        """Close a connection to a store.

        :param bool commit_pending_transaction: True if to commit pending transaction before closing, False otherwise.

        .. note::
            The graph.close() method is not implemented for SPARQL Store in RDFLib
        """
        self.graph.close(commit_pending_transaction=commit_pending_transaction)
开发者ID:vincent-octo,项目名称:ktbs_bench_manager,代码行数:41,代码来源:benchable_graph.py

示例14: main

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]
def main():
    # Track executing time
    # start_time = time.time()
    headers = {'content-type': 'application/json'}  # HTTP header content type
    # Configurations
    config = ConfigParser()
    config.read('config.ini')
    
    endpoint_uri = config['Mandatory']['endpointURI']
    graph_uri = config['Mandatory']['graphURI']
    pool_uri = (config['Mandatory']['poolURI']).split(',')
    type_uri = (config['Mandatory']['typeURI']).split(',')

    # Set up endpoint and access to triple store
    sparql = SPARQLWrapper(endpoint_uri)
    sparql.setReturnFormat(JSON)
    sparql.setMethod(POST)
    store = SPARQLUpdateStore(endpoint_uri, endpoint_uri)

    # Specify the (named) graph we're working with
    sparql.addDefaultGraph(graph_uri)

    # Create an in memory graph
    g = Graph(store, identifier=graph_uri)

    # Build the RDF from the JSON source data
    # This function is to be called for each URL in the pool to harvest, in case that the source is in json, with the Estonian mapping
    def rdf(urlrdf, f):
        input = Graph()
        input.open("store2", create=True)
        input.parse(urlrdf, format=f)
        
        for s, p, o in input:
            g.add((s, p, o))

        input.close()

    # Set counter
    c = 0

    # Loop over all URI in the pool
    while c < len(pool_uri):
        print(pool_uri[c],type_uri[c])
        if type_uri[c] == 'jsonEstonia':
            try:
                # Fetch the JSON data
                response = requests.get(pool_uri[c], headers=headers).json()

                # Process the response
                configJSON = ConfigParser()
                configJSON.read('mapping_estonia.ini')
                json_to_rdf(pool_uri[c], response, g, configJSON)
    
            except ValueError as e:
                print(e)
                
        if type_uri[c] == 'xml' or type_uri[c] == 'turtle' or type_uri[c] == 'nt':
            rdf(pool_uri[c], type_uri[c])


        # Counter update
        c += 1

    # Iterate over triples in store and print them out.
    print('\r\nNumber of triples added: %d' % len(g))
    
    # Cleanup the graph instance
    g.close()
开发者ID:catalogue-of-services-isa,项目名称:cpsv-ap_harvester,代码行数:70,代码来源:harvester.py

示例15: main

# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import close [as 别名]

#.........这里部分代码省略.........
                creator_list = item_dict['creator']
                #Get record identifier
                record_id_url = urlparse(item_dict['identifier'][0])
                record_id = record_id_url.path.replace('/', '')
                #Iterate over each creator of the current record
                for creator in creator_list:
                    creator_orig = creator                    
                    if creator_orig not in creator_dict.keys():
                        creator = creator.replace(' ', '%20')
                        creator_params = urllib.urlencode({'query': creator.encode('utf-8')})
                        req = urllib2.Request('http://viaf.org/viaf/AutoSuggest?' + creator_params)
                        f = urllib2.urlopen(req)
                        try:
                            json_item = simplejson.load(f, strict=False)
                        except Exception as e:
                            print e
                            break
                        #Generate creator id
                        #id_len = len(str(creator_id_count))
                        #digits = CREATOR_ID_DIGITS - id_len
                        #id_formatter = '%0' + str(digits) + 'd'
                        creator_id = creator_id_count
                        creator_id_count = creator_id_count + 1
                        
                        #Get results from VIAF (if any)
                        if json_item['result']:
                            viaf_id = json_item['result'][0]['viafid']
                            
                            #Create new Creator instance
                            creator = Creator(creator_orig, creator_id, viaf_id)
                        else:
                            #Create new Creator instance
                            creator = Creator(creator_orig, creator_id)
                        creator_dict[creator_orig] = creator
                        record_creator_list.append(creator)
                    else:
                        record_creator_list.append(creator_dict[creator_orig])
                
                item_dict['creator'] = record_creator_list
                item_type_list = item_dict['type']
                if type(item_type_list) == list:
                    for item_type in item_type_list:
                        if item_type.encode('utf-8') == 'Artículo':
                            #print 'Articulo'
                            g.add((RDF_DOMAIN + u'resource/biblio/' + record_id, u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', u'http://purl.org/ontology/bibo/Article'))
                        elif item_type.encode('utf-8') == 'Sección de Libro':
                            #print 'Seccion'
                            g.add((RDF_DOMAIN + u'resource/biblio/' + record_id, u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', u'http://purl.org/ontology/bibo/BookSection'))
                        elif item_type == u'Libro':
                            #print 'Libro'
                            g.add((RDF_DOMAIN + u'resource/biblio/' + record_id, u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', u'http://purl.org/ontology/bibo/Book'))
                        elif item_type == u'PeerReviewed':
                            #print 'Peer'
                            g.add((RDF_DOMAIN + u'resource/biblio/' + record_id, u'http://purl.org/ontology/bibo/DocumentStatus', u'http://purl.org/ontology/bibo/status/peerReviewed'))
                        elif item_type.encode('utf-8') == 'Monografía':
                            g.add((RDF_DOMAIN + u'resource/biblio/' + record_id, u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', u'http://purl.org/ontology/bibo/Document'))
                

                else:
                    item_type = item_dict['type']
                    if item_type.encode('utf-8') == 'Artículo':
                        #print 'Articulo'
                        g.add((RDF_DOMAIN + u'resource/biblio/' + record_id, u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', u'http://purl.org/ontology/bibo/Article'))
                    elif item_type.encode('utf-8') == 'Sección de Libro':
                        #print 'Seccion'
                        g.add((RDF_DOMAIN + u'resource/biblio/' + record_id, u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', u'http://purl.org/ontology/bibo/BookSection'))
                    elif item_type == u'Libro':
                        #print 'Libro'
                        g.add((RDF_DOMAIN + u'resource/biblio/' + record_id, u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', u'http://purl.org/ontology/bibo/Book'))
                    elif item_type == u'PeerReviewed':
                        #print 'Peer'
                        g.add((RDF_DOMAIN + u'resource/biblio/' + record_id, u'http://purl.org/ontology/bibo/DocumentStatus', u'http://purl.org/ontology/bibo/status/peerReviewed'))
                    elif item_type.encode('utf-8') == 'Monografía':
                        g.add((RDF_DOMAIN + u'resource/biblio/' + record_id, u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', u'http://purl.org/ontology/bibo/Document'))
                
                for key in item_dict:
                    obj = item_dict[key]
                    if type(obj) == list:
                        for creator_item in obj:
                            if key == 'creator':
                                g.add((RDF_DOMAIN + u'resource/biblio/' + record_id, u'http://purl.org/dc/elements/1.1/creator', RDF_DOMAIN + u'resource/author/' + str(creator_item.id)))
                            else:
                                g.add((RDF_DOMAIN + u'resource/biblio/' + record_id, u'http://purl.org/dc/elements/1.1/' + key, Literal(creator_item)))
                                
    for key in creator_dict.keys():
        creator = creator_dict[key]
        g.add((RDF_DOMAIN + u'resource/author/' + str(creator.id), u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', u'http://xmlns.com/foaf/0.1/Person'))
        g.add((RDF_DOMAIN + u'resource/author/' + str(creator.id), u'http://xmlns.com/foaf/0.1/name', Literal(creator.name)))
        if creator.viaf_id != None:
            g.add((RDF_DOMAIN + u'resource/author/' + str(creator.id), u'http://www.w3.org/2002/07/owl#sameAs', VIAF_URL + creator.viaf_id))
                                
    print len(g)

    #for s, p, o in g:
        ##print s, p, o

    f = open('hedatuz.rdf', 'w')
    f.write(g.serialize(format='pretty-xml'))
    g.close()
    f.close()
开发者ID:memaldi,项目名称:hedatuz2rdf,代码行数:104,代码来源:hedatuz2rdf.py


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