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


Python Graph.subjects方法代码示例

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


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

示例1: handle

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import subjects [as 别名]
    def handle(self, *args, **options):
        from rdflib.graph import Graph
        from rdflib import RDFS, RDF, OWL
        from rdflib.term import URIRef, BNode, Literal
        import yaml

        OboDefinition = URIRef('http://purl.obolibrary.org/obo/IAO_0000115')
        part_of_some = URIRef('http://purl.obolibrary.org/obo/BFO_0000050_some')
        Synonym = URIRef(u'http://www.geneontology.org/formats/oboInOwl#hasSynonym')

        g = Graph()
        g.parse(args[1], 'xml')

        Model = MuscleOwl if args[0] == 'm' else BehaviorOwl

        # first pass, add the things
        for subject in nonblankthings(g, g.subjects()):
            slabel = g.label(subject)
            m = get_model_instance(Model, unicode(subject))
            m.uri = unicode(subject)
            m.label = unicode(slabel)

            m.rdfs_is_class = (subject, RDF.type, OWL.Class) in g
            m.obo_definition = unicode(g.value(subject, OboDefinition, None))
            m.rdfs_comment = unicode(g.value(subject, RDFS.comment, None))
            synonyms = [unicode(syn) for syn in g.objects(subject, Synonym)]
            if len(synonyms):
                m.synonyms_comma_separated = ", ".join(synonyms)
            else:
                m.synonyms_comma_separated = None

            m.save()

        # second pass, add the relationships
        for subject in nonblankthings(g, g.subjects()):
            slabel = g.label(subject)
            m = Model.objects.get(uri=unicode(subject))

            m.rdfs_subClassOf_ancestors.clear()
            # add all super-classes to m.rdfs_subClassOf_ancestors
            for obj in nonblankthings(g, g.transitive_objects(subject, RDFS.subClassOf)):
                if obj != subject:
                    a = Model.objects.get(uri=unicode(obj))
                    m.rdfs_subClassOf_ancestors.add(a)

            m.bfo_part_of_some.clear()
            # add all things that this thing is part of to m.bfo_part_of_some
            for obj in nonblankthings(g, g.objects(subject, part_of_some)):
                if obj != subject:
                    a = Model.objects.get(uri=unicode(obj))
                    m.bfo_part_of_some.add(a)

            # add only direct super-classes to m.rdfs_subClassOf
            #for obj in nonblankthings(g, g.objects(subject, RDFS.subClassOf)):
            #    if obj != subject:
            #        a = Model.objects.get(uri=unicode(obj))
            #        m.rdfs_subClassOf.add(a)

            m.save()
开发者ID:NESCent,项目名称:feedingdb,代码行数:61,代码来源:loadowl.py

示例2: canvases

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import subjects [as 别名]
def canvases(uri):
    g = Graph(store=rdfstore(), identifier=URIRef(uri))
    
    subjs = [str(i) for i in g.subjects(NS.rdf['type'], NS.sc['Canvas'])]
    if len(subjs) == 0:
        subjs = [str(i) for i in g.subjects(NS.rdf['type'], NS.dms['Canvas'])]

    return subjs
开发者ID:bobclewell,项目名称:DM,代码行数:10,代码来源:manuscripts.py

示例3: project_export_graph

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import subjects [as 别名]
def project_export_graph(project_uri):
    db_project_graph = get_project_graph(project_uri)
    db_metadata_graph = get_project_metadata_graph(project_uri)
    export_graph = Graph()
    export_graph += db_project_graph
    export_graph += db_metadata_graph

    for text_uri in export_graph.subjects(NS.rdf.type, NS.dcmitype.Text):
        export_graph += text_graph_from_model(text_uri, project_uri)

    return export_graph
开发者ID:timandres,项目名称:DM,代码行数:13,代码来源:projects.py

示例4: test_create_user_project

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import subjects [as 别名]
    def test_create_user_project(self):
        url = reverse('semantic_store_projects', kwargs=dict())
        g = Graph()
        bind_namespaces(g)
        project = BNode()
        title = Literal("This is a project title")
        g.add((project, NS.rdf['type'], NS.dcmitype['Collection']))
        g.add((project, NS.rdf['type'], NS.ore['Aggregation']))
        g.add((project, NS.dc['title'], title))
        data = g.serialize(initNs=ns)
        response = self.client.post(url, data=data, content_type="text/xml")
        self.assertEqual(response.status_code, 201)

        self.assertGreater(len(response.content), 0)
        response_g = Graph()
        response_g.parse(data=response.content)
        uris = list(response_g.subjects(NS.dc['title'], title))
        self.assertGreater(len(uris), 0)

        uri_assigned = uris[0]
        self.assertTrue((uri_assigned, NS.rdf['type'], NS.dcmitype['Collection']) \
                            in response_g)
        self.assertTrue((uri_assigned, NS.rdf['type'], NS.ore['Aggregation']) \
                            in response_g)
开发者ID:bobclewell,项目名称:DM,代码行数:26,代码来源:tests.py

示例5: _load_rules

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import subjects [as 别名]
 def _load_rules(self, rules_file_name):
     # Rules are stored in hash map
     rules = {}
     
     # Load the rule base into memory
     logger.debug('Loading {}'.format(rules_file_name))
     g = Graph().parse(rules_file_name, format="turtle")
     
     # Extract the namespaces from the rule base
     r_ns = {}
     for (ns, uri) in g.namespaces():
         r_ns[ns] = uri
     
     # Compose and prepare the SPARQL queries
     for s in g.subjects(RDF.type, INDEXER.Rule):
         # Extract the components of the rule
         r_if = g.value(s, INDEXER['if']).toPython().replace('\t', '')
         r_then = g.value(s, INDEXER['then']).toPython().replace('\t', '')
         rule = 'CONSTRUCT {' + r_then + '} WHERE {' + r_if + '}'
         
         # Pre-load the rule
         rules[s.toPython()] = prepareQuery(rule, initNs=r_ns)
 
     return rules
开发者ID:cgueret,项目名称:Indexer,代码行数:26,代码来源:process.py

示例6: Graph

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import subjects [as 别名]
    (options, args) = parser.parse_args()

    owlGraph = Graph()
    for input in args[0:]:
        if options.verbose:
            print("Parsing ", input, " as ", options.format)
        owlGraph.parse(input, format=options.format)

    Individual.factoryGraph = owlGraph

    def topList(node, g):
        for s in g.subjects(RDF.rest, node):
            yield s

    for negativeClass in owlGraph.subjects(predicate=OWL_NS.complementOf):
        containingList = first(owlGraph.subjects(RDF.first, negativeClass))
        prevLink = None
        while containingList:
            prevLink = containingList
            containingList = first(owlGraph.subjects(RDF.rest, containingList))
        for s, p, o in owlGraph.triples_choices((None,
                                                 [OWL_NS.intersectionOf,
                                                  OWL_NS.unionOf],
                                                 prevLink)):
            _class = Class(s)
            # print(_class.__repr__(True,True))
            ComplementExpansion(_class, debug=options.verbose)


# from FuXi.Horn import ComplementExpansion
开发者ID:RDFLib,项目名称:FuXi,代码行数:32,代码来源:__init__.py

示例7: ttl2solr

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import subjects [as 别名]
def ttl2solr(infile, outfile, vocab_name=None):
    logger.info('ttl2solr: Loading %s', infile)
    g = Graph()
    g.load(infile, format='turtle')

    # Build parent lookup hash
    # logger.debug('Building parent lookup hash')
    parents = {}
    for c, p in g.subject_objects(SKOS.broader):
        c = text_type(c)  # to string
        p = text_type(p)  # to string
        if c not in parents:
            parents[c] = set()
        parents[c].add(p)

    # Build labels lookup hash using two fast passes
    # logger.debug('Building labels lookup hash')
    labels = {}
    for c, p in g.subject_objects(SKOS.altLabel):
        labels[text_type(c)] = text_type(p)
    for c, p in g.subject_objects(SKOS.prefLabel):
        labels[text_type(c)] = text_type(p)  # overwrite altLabel with prefLabel if found

    # logger.debug('Building documents')
    docs = []
    unknown_preds = set()
    for uriref in g.subjects(RDF.type, SKOS.Concept):
        doc = {'id': text_type(uriref)}
        if vocab_name is not None:
            doc['vocabulary'] = vocab_name

        for pred, obj in g.predicate_objects(uriref):
            if pred not in schema:
                if pred not in unknown_preds:
                    logger.warning('Encountered unknown predicate with no mapping to JSON: %s', pred)
                    unknown_preds.add(pred)
                continue
            if pred == SKOS.inScheme and schema[pred] in vocabs:
                doc['vocab'] = vocabs[schema[pred]]
                continue
            if schema[pred] is None:
                continue
            if schema[pred] not in doc:
                doc[schema[pred]] = []

            doc[schema[pred]].append(text_type(obj))

        # Add labels from broader concepts

        bcs = []
        for bc in get_breadcrumbs([[text_type(uriref)]], parents):
            bc = [labels.get(x) for x in reversed(bc[1:])]
            bcs.append('/'.join([x for x in bc if x is not None]))
        doc['paths'] = bcs

        byLevel = [[text_type(uriref)]]  # Level 0
        level = 0
        while True:
            byLevel.append([])
            for x in byLevel[level]:
                byLevel[level + 1].extend(parents.get(x, set()))
            if len(byLevel[level + 1]) == 0:
                break
            level += 1

        for level, items in enumerate(byLevel[1:4]):
            # logger.debug(level, items)
            doc['parentsLevel{}'.format(level + 1)] = [labels[x] for x in items if x in labels]  # Vi mangler labels for enkelt toppetiketter, som f.eks. 'http://data.ub.uio.no/ddc/19'

        docs.append(doc)
    logger.info('ttl2solr: Storing %d documents in %s', len(docs), outfile)
    json.dump(docs, open(outfile, 'w'), indent=2)
开发者ID:scriptotek,项目名称:data_ub_tasks,代码行数:74,代码来源:ttl2solr.py

示例8: Graph

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import subjects [as 别名]
g = Graph()

# Bind a few prefix, namespace pairs.
g.bind("dc", "http://http://purl.org/dc/elements/1.1/")
g.bind("foaf", "http://xmlns.com/foaf/0.1/")

# Create a namespace object for the Friend of a friend namespace.
FOAF = Namespace("http://xmlns.com/foaf/0.1/")

# Create an identifier to use as the subject for Donna.
donna = BNode()

# Add triples using store's add method.
g.add((donna, RDF.type, FOAF["Person"]))
g.add((donna, FOAF["nick"], Literal("donna", lang="foo")))
g.add((donna, FOAF["name"], Literal("Donna Fales")))

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

# For each foaf:Person in the store print out its mbox property.
print("--- printing mboxes ---")
for person in g.subjects(RDF.type, FOAF["Person"]):
    for mbox in g.objects(person, FOAF["mbox"]):
        print(mbox)
        
        
开发者ID:huanjiayang,项目名称:SWoT,代码行数:29,代码来源:main.py

示例9: __init__

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

#.........这里部分代码省略.........
		'''	
		for place in rss.getElementsByTagName('place'):
			name1 = place.getElementsByTagName('name1')[0].firstChild.nodeValue
			blogger_id1 = place.getElementsByTagName('blogger-id')[0].firstChild.nodeValue
			title1 = place.getElementsByTagName('title')[0].firstChild.nodeValue
			url1 = place.getElementsByTagName('url')[0].firstChild.nodeValue
			date1 = place.getElementsByTagName('date')[0].firstChild.nodeValue
			expense = place.getElementsByTagName('expense')[0].firstChild.nodeValue
			
			
			blog  = self.nsDict['blog']
			foaf = self.nsDict['foaf']
			dcterms = self.nsDict['dcterms'] 
			self.graph.add((blog,blogger_id1,Literal(blogger_id1)))
			self.graph.add((blog[blogger_id1],foaf['name'],Literal(name1)))
			self.graph.add((blog[blogger_id1],dcterms['title'],Literal(title1)))
			self.graph.add((blog[blogger_id1],dcterms['date'],Literal(date1)))
		'''
			
		self.graph.commit()

	def open_store(self):
		default_graph_uri = "http://rdflib.net/rdfstore"
		# open existing store or create new one
		#store = getStore() # if store does not exist, then new store returned
		
		# RDF store section:
		configString = "/var/tmp/rdfstore"
		
		# Get the Sleepycat plugin.
		store = plugin.get('Sleepycat', Store)('rdfstore')		
		# Open previously created store, or create it if it doesn't exist yet
		path = mkdtemp()
		rt = store.open('rdfstore', create=False)
		#print rt
		#print path
		
		if rt == NO_STORE:
			print "Creating new store"
			# There is no underlying Sleepycat infrastructure, create it
			store.open('rdfstore', create=True)        
		else:
			print "store exists "
			#assert rt == VALID_STORE, "The underlying store is corrupt"

		self.graph = Graph(store,identifier = URIRef(default_graph_uri))		
		self.build_graph()	
		        				        
		'''
		print_RDF_triples(graph)
		#print_RDF_XML(graph)
		graph.commit()
		#create_RDF_File(graph)
		graph.close(commit_pending_transaction=True)

		'''

	def run_Query(self,queryString):
		qres = self.graph.query(queryString,
							initNs=dict(foaf=Namespace("http://xmlns.com/foaf/0.1/"),
							blog = Namespace('http://rdflib.net/blog/'),
							blogger_id = Namespace('http://rdflib.net/blog/blogger_id/'))
							)
		for row in qres.result:
			print row
	
	
	def print_RDF_XML(self):
	    #print graph.serialize(format="pretty-xml")
	    print self.graph.serialize()

	def print_RDF_triples(self):
		print "Triples in graph after add: ", len(graph)
		
		#Iterate over triples in graph and print them out.
		print "--- printing raw triples ---"
		for s, p, o in self.graph:
		        print s, p, o

	def print_RDF_Maker(self):
	    # For each foaf:Project in the self.graph print out its maker.
	    print "--- printing MAKERS ---"
	    for game in self.graph.subjects(RDF.type, FOAF["Project"]):
	            for madeby in self.graph.objects(game, FOAF["maker"]):
	                    print madeby
			
	def removeFromStore(self):
		rdflib = Namespace('http://rdflib.net/games/')
		self.graph.bind("game", "http://rdflib.net/games/")
		self.graph.remove((rdflib['game:2'], rdflib['name'], Literal('Ignition')))
		self.graph.commit()
		#str(graph)

	def sample_query(self, querystring):
	    print "Query enter"
	    processor = plugin.get('sparql', rdflib.query.Processor)(self.graph)
	    result = plugin.get('sparql', rdflib.query.Result)
	    
	    ns = dict(self.graph.namespace_manager.namespaces())
	    return result(processor.query(querystring, initNs=ns))
开发者ID:shreeshga,项目名称:BlogCrawler,代码行数:104,代码来源:rdflibmethods.py

示例10: Namespace

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import subjects [as 别名]
snotes = Namespace('http://my.sourcenotes.org/2006/04/sourcenotes#')
heml = Namespace('http://www.heml.org/schemas/2003-09-17/heml#')
rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
rdfs = Namespace('http://www.w3.org/2000/01/rdf-schema#')
dc = Namespace('http://purl.org/dc/elements/1.1/')
dct = Namespace('http://purl.org/dc/terms/')
rel = Namespace('http://www.perceive.net/schemas/20021119/relationship#')
pome = Namespace('http://prosopOnto.medieval.england/2006/04/pome#')
crm = Namespace('http://cidoc.ics.forth.gr/rdfs/cidoc_v4.2.rdfs#')
me = Namespace('file:///Users/jjc/Documents/Dissertation/Notes/1233HostageDeal/modelTesting/1233Hostages.rdf#')


g = Graph()
g.parse("/Users/jjc/Documents/Dissertation/Notes/1233HostageDeal/modelTesting/hostages8.n3", format='n3')

exchanges = list(g.subjects(rdf['type'],crm['Event']))
people = list(g.subjects(rdf['type'], pome['Person']))
pdict = {}
for x in people:
    person = x.split('#')[1]
    if person not in pdict:
        pdict[person] = True

pprint(pdict)
# 
#         
# def test_a():
#     g = Graph()
#     g.parse(data=rdf, format='n3')
#     v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel"))
#     assert v==u"C\u00f4te d'Ivoire"
开发者ID:jjon,项目名称:HARE,代码行数:33,代码来源:rdflib2nativepy.py

示例11: get_graph_from_uri

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import subjects [as 别名]
    def get_graph_from_uri(self, foaf_uri):
        graph = Graph()
        [graph.bind(*x) for x in ns_profile.items()]

        # getting the public foaf and inserting into the graph

        # FIXME
        # cant retrieve directly the url, GAE doesn't allow open sockets:
        # sock = socket.create_connection((self.host, self.port),
        # AttributeError: 'module' object has no attribute 'create_connection'
        #store.parse(location)
        #response = get_private_uri(foaf_uri, HUB_CERTIFICATE, HUB_KEY)
        #foaf = response.read()

        # workaround using GAE urlfetch...
        #response = urlfetch.fetch(foaf_uri, validate_certificate=False)
        # passing certificate in another manual way...
        
        # not able either to open files
        #raise IOError(errno.EACCES, 'file not accessible', filename)
        #cert_file = open(HUB_CERTIFICATE_P12)
        #cert_data = cert_file.read()
        #response = urlfetch.fetch(foaf_uri, 
        #                          payload = cert_data
        #                          method=urlfetch.POST,
        #                          headers={'Content-Type': "application/x-x509-user-cert",
        #                                   'webid_uri': HUB_WEBID},
        #                          validate_certificate=False)
        
        # timeout due to it is processing the subscriber cert and webid requests?
        form_fields = {"cert_uri": HUB_CERTIFICATE_URI, "webid_uri": HUB_WEBID}
        form_data = urllib.urlencode(form_fields)
        response = urlfetch.fetch(url=foaf_uri,
                        payload=form_data,
                        method=urlfetch.POST,
                        headers={'Content-Type': 'application/x-www-form-urlencoded'},
                        validate_certificate=False,
                        deadline=60)

        # assert self.__rpc.state != apiproxy_rpc.RPC.IDLE, repr(self.state)
        # AssertionError: 0
        #rpc = urlfetch.create_rpc()
        #rpc.callback = self.create_callback(rpc)
        #rpc.deadline = 60
        #urlfetch.make_fetch_call(rpc = rpc,
        #                url=foaf_uri,
        #                payload=form_data,
        #                method=urlfetch.POST,
        #                headers={'Content-Type': 'application/x-www-form-urlencoded'},
        #                follow_redirects = True)
        #rpc.wait()

        foaf = response.content
        content_type = response.headers['content-type'].split(';')[0]
        logging.info(content_type)
        #logging.debug(response.status_code)
        #if response.status_code == 200:
        logging.info("foaf: " + foaf)


        # can't parse n3 with GAE
        # rdflib/plugins/parsers/notation3.py", line 417, in runNamespace
        # base(), ".run-" + `time.time()` + "p"+ `os.getpid()` +"#")
        # AttributeError: 'module' object has no attribute 'getpid'
        #graph.parse(data=foaf, format="n3")
        
        # GAE doesn't allow to write to the filesystem either
        #f = open('temp.nt','w')
        #f.write(foaf)
        #f.close()
        #graph.parse('temp.nt', format="nt")

        # but can parse rdf+xml, so converting to it...
        graph.parse(data=foaf, format=parsers[content_type])

        # No need for the query, we can get person(s) from foaf directly from 
        # the graph
        # FIXME: what if there're more than one persons?
        person_URI = [p for p in graph.subjects(RDF.type, FOAF["Person"])][0]
        return graph
开发者ID:janaya,项目名称:pubsubhubbub-sempush,代码行数:82,代码来源:profile_manager.py

示例12: BNode

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import subjects [as 别名]
# Create an identifier to use as the subject for Donna.
donna = BNode()

# Add triples using store's add method.
store.add((donna, RDF.type, FOAF["Person"]))
store.add((donna, FOAF["nick"], Literal("donna", lang="foo")))
store.add((donna, FOAF["name"], Literal("Donna Fales")))

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

# For each foaf:Person in the store print out its mbox property.
print("--- printing mboxes ---")
for person in store.subjects(RDF.type, FOAF["Person"]):
    for mbox in store.objects(person, FOAF["mbox"]):
        print(mbox)

# Serialize the store as RDF/XML to the file foaf.rdf.
# store.serialize("foaf.rdf", format="pretty-xml", max_depth=3)

# Let's show off the serializers

print("RDF Serializations:")

# Serialize as XML
print("--- start: rdf-xml ---")
print(store.serialize(format="pretty-xml"))
print("--- end: rdf-xml ---\n")
开发者ID:SpazioDati,项目名称:rdflib,代码行数:32,代码来源:simple_example.py

示例13: Graph

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import subjects [as 别名]
added = Graph()
added.load('realfagstermer/added.nt', format='nt')

logging.info('Loading realfagstermer.new.nt as <current>')
current = Graph()
current.load('realfagstermer/realfagstermer.new.nt', format='nt')
current.namespace_manager.bind('skos', SKOS)
current.namespace_manager.bind('mads', MADS)
current.namespace_manager.bind('dct', DCTERMS)


logging.info('Computing')

changes = []

removed_subjects = set(removed.subjects())
added_subjects = set(added.subjects())
subjects = added_subjects.union(removed_subjects)

# TODO: Sort subjects by dct:modified ?? Eller er det bedre å ha det alfabetisk som nå?

notInteresting = [DCTERMS.modified, RDF.type, SKOS.inScheme]


def get_label(concept, set1, set2, set3, lang='nb'):
    label = set1.preferredLabel(concept, lang=lang)
    if len(label) == 0:
        label = set2.preferredLabel(concept, lang=lang)
    if len(label) == 0:
        label = set3.preferredLabel(concept, lang=lang)
    if len(label) == 0:
开发者ID:realfagstermer,项目名称:realfagstermer-publish,代码行数:33,代码来源:diff_test.py

示例14: convert

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import subjects [as 别名]
def convert(infile, outfile):
    logger.debug('Loading %s', infile)
    g = Graph()
    g.load(infile, format='turtle')

    # Build parent lookup hash
    logger.debug('Building parent lookup hash')
    parents = {}
    for c, p in g.subject_objects(SKOS.broader):
        c = text_type(c)  # to string
        p = text_type(p)  # to string
        if c not in parents:
            parents[c] = set()
        parents[c].add(p)

    # Build labels lookup hash using two fast passes
    logger.debug('Building labels lookup hash')
    labels = {}
    for c, p in g.subject_objects(SKOS.altLabel):
        labels[text_type(c)] = text_type(p)
    for c, p in g.subject_objects(SKOS.prefLabel):
        labels[text_type(c)] = text_type(p)  # overwrite altLabel with prefLabel if found

    logger.debug('Building documents')
    docs = []
    for uriref in g.subjects(RDF.type, SKOS.Concept):
        doc = {'id': text_type(uriref)}

        for pred, obj in g.predicate_objects(uriref):
            if pred not in schema:
                logger.error('Encountered unknown predicate with no mapping to JSON: %s', pred)
                continue
            if pred == SKOS.inScheme and schema[pred] in vocabs:
                doc['vocab'] = vocabs[schema[pred]]
                continue
            if schema[pred] is None:
                continue
            if schema[pred] not in doc:
                doc[schema[pred]] = []

            doc[schema[pred]].append(text_type(obj))

        # Add labels from broader concepts

        byLevel = [[text_type(uriref)]]  # Level 0
        level = 0
        while True:
            byLevel.append([])
            for x in byLevel[level]:
                byLevel[level + 1].extend(parents.get(x, set()))
            if len(byLevel[level + 1]) == 0:
                break
            level += 1

        for level, items in enumerate(byLevel[1:-1]):
            # logger.debug(level, items)
            doc['parentsLevel{}'.format(level)] = [labels[x] for x in items if x in labels]  # Vi mangler labels for enkelt toppetiketter, som f.eks. 'http://data.ub.uio.no/ddc/19'

        docs.append(doc)
    logger.debug('Generated %d documents', len(docs))

    logger.debug('Saving %s', outfile)
    json.dump(docs, open(outfile, 'w'), indent=2)
开发者ID:danmichaelo,项目名称:ubdata-tools,代码行数:65,代码来源:ttl2solr.py

示例15: Namespace

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

##--------------------##
# Checking keywords in objectives
graphUSDL4EDU=Graph()
graphUSDL4EDU.parse("\commondata\usdl4edu.ttl",format='n3')
USDL4EDU = Namespace("http://rdf.genssiz.dei.uc.pt/usdl4edu#")
DC = Namespace("http://purl.org/dc/terms/")


graphConcepts=Graph()
graphConcepts.parse("\commondata\exported\context.ttl",format='n3')
SKOS = Namespace("http://www.w3.org/2004/02/skos/core#")

keywords=[]
for obj in graphUSDL4EDU.subjects(RDF.type,USDL4EDU["KnowledgeDimension"]):
	# aux=[]
	for mbox in graphUSDL4EDU.objects(obj,USDL4EDU["hasKeyword"]):
		# aux.append(str(mbox))
		keywords.append(str(mbox))
		print mbox
print keywords
# graph=Graph()
# graph.parse("\commondata\exported\udacity.ttl",format='n3')
# description=""
# number_descriptions=0
# number_found=0
# number_context=0
# for obj in graph.subjects(RDF.type,USDL4EDU["OverallObjective"]):
# 	for mbox in graph.objects(obj,DC["description"]):
# 		number_descriptions+=1
开发者ID:jduro,项目名称:esoteric,代码行数:32,代码来源:rdf_test.py


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