本文整理汇总了Python中rdflib.Graph.subjects方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.subjects方法的具体用法?Python Graph.subjects怎么用?Python Graph.subjects使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.Graph
的用法示例。
在下文中一共展示了Graph.subjects方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_catalog_pagination
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def test_catalog_pagination(self):
for i in xrange(12):
factories.Dataset()
app = self._get_test_app()
url = url_for('dcat_catalog', _format='rdf')
response = app.get(url)
content = response.body
g = Graph()
g.parse(data=content, format='xml')
eq_(len([d for d in g.subjects(RDF.type, DCAT.Dataset)]), 10)
pagination = [o for o in g.subjects(RDF.type, HYDRA.PagedCollection)][0]
eq_(self._object_value(g, pagination, HYDRA.totalItems), '12')
eq_(self._object_value(g, pagination, HYDRA.itemsPerPage), '10')
eq_(self._object_value(g, pagination, HYDRA.firstPage),
url_for('dcat_catalog', _format='rdf', page=1, host='localhost'))
eq_(self._object_value(g, pagination, HYDRA.nextPage),
url_for('dcat_catalog', _format='rdf', page=2, host='localhost'))
eq_(self._object_value(g, pagination, HYDRA.lastPage),
url_for('dcat_catalog', _format='rdf', page=2, host='localhost'))
示例2: get
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def get(self):
out = []
if 1:
g = Graph()
g.parse("http://bang:9103/graph", format="n3")
tasks = [] # (pos, task)
for t in g.subjects(RDF.type, CV.OpenTask):
if (None, CV.child, t) in g:
continue
tasks.append((g.value(t, CV.position), t))
tasks.sort()
def appendTree(t, depth):
out.append(dict(
uri=t,
depth=depth,
mark=g.value(t, CV.mark),
content=g.value(t, CV.content),
))
for sub in g.objects(t, CV.child):
if (sub, RDF.type, CV.OpenTask) not in g:
continue
appendTree(sub, depth+1)
for pos, t in tasks[:10]:
appendTree(t, depth=0)
events = [] # [{'date':'yyyy-mm-dd', 'dayEvents':[], 'timeEvents':[]}]
g = Graph()
g.parse("http://bang:9105/events?days=3", format='n3')
byDay = {}
for ev in g.subjects(RDF.type, EV.Event):
start = g.value(ev, EV['start'])
s = parse(start)
d = s.date().isoformat()
byDay.setdefault(d, {'dayEvents':[],
'timeEvents':[]})[
'timeEvents' if 'T' in start else 'dayEvents'].append({
'title' : g.value(ev, EV['title']),
'start' : start,
'date' : s.date().isoformat(),
'time' : s.time().isoformat()[:-3],
})
for k,v in sorted(byDay.items(), key=lambda (k,v): k):
d = {'date':k, 'weekdayName':parse(k).strftime("%A")}
d.update(v)
d['dayEvents'].sort(key=lambda ev: ev['title'])
d['timeEvents'].sort(key=lambda ev: ev['start'])
events.append(d)
self.write(json.dumps({'tasks':out, 'events' : events}))
示例3: parse_owl
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def parse_owl(url, id, annotype):
"""" Download and parse owl files to return a dictionary of annotation values,
where the unique identifier is the key and the name is the value,
and the version and date information for the owl file. """
# change working directory to 'source-data'
if not os.path.exists('source-data'):
os.mkdir('source-data')
os.chdir('source-data')
anno_dict = {}
version = None
owl = Graph()
owl.parse(get_data(url))
try:
ontology = [s for s in owl.subjects(RDF.type, OWL.Ontology)][0]
except:
print("No Ontology URI for {0}".format(url))
ver = owl.value(ontology, OWL.versionIRI)
if ver: # 1st try getting version and date from versionIRI
version = str(ver)
pub_date = version.split('/')[-2]
if not version: # 2nd try getting version from versionInfo
ver = owl.value(ontology, OWL.versionInfo)
if ver:
version = str(ver[0])
pub_date = owl.value(ontology, DC.date)
if not pub_date: # last try getting date from Ontology comments
for o in owl.objects(ontology, RDFS.comment):
if str(o).startswith('Date:'):
pub_date = str(o).split(':')[-1].strip()
pub_date = datetime.datetime.strptime(pub_date, '%dth %B %Y')
pub_date = pub_date.strftime('%Y-%m-%d')
print(version)
print(pub_date)
if id == 'EFO': # only using cell_lines from EFO, make list of Classes
cell_lines = [q[0] for q in owl.query(
'SELECT * WHERE {?s rdfs:subClassOf+ <http://www.ebi.ac.uk/efo/EFO_0000322>}')]
for s in owl.subjects(RDF.type, OWL.Class):
val = owl.label(s)
term = str(s).split('/')[-1]
obsolete = owl.value(s, OWL.deprecated)
if val and term.startswith(id) and not obsolete:
if id == 'EFO' and s not in cell_lines:
continue
else:
anno_dict[term] = val
os.chdir(os.pardir)
return anno_dict, ver, pub_date
示例4: test_get_smart_allergies
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def test_get_smart_allergies(self):
# allergies are a special case since they can be an Allergy or AllergyExclusion
response = self.client.get('/records/%s/allergies/'%(self.record.id))
self.assertEquals(response.status_code, 200)
g = Graph()
g.parse(data=response.content, format="application/rdf+xml")
allergy_results = [l for l in g.subjects(None,SMART["Allergy"])]
self.assertEqual(len(allergy_results), 1)
allergy_exclusion_results = [l for l in g.subjects(None,SMART["AllergyExclusion"])]
self.assertEqual(len(allergy_exclusion_results), 0)
# retrieve a single allergy
allergy_id = allergy_results[0].split('/')[-1]
response = self.client.get('/records/%s/allergies/%s' % (self.record.id, allergy_id))
self.assertEquals(response.status_code, 200)
示例5: __init__
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
class nerd:
def __init__(self, source, format):
self.source = source
self.format = format
self.graph = Graph()
self.result = self.graph.parse(source, format=format)
def get_subjects(self, predicate, object):
res = self.graph.subjects(predicate=URIRef(owl+predicate), object=URIRef(alchemyapi+object))
result = []
for k in res:
result.append(k)
return result
# return self.graph.subjects(predicate, object)
def get_subClasses(self, subject, predicate):
res = self.graph.objects(subject=URIRef("http://searchet.baidu.com/ontology#"+subject), predicate=URIRef("http://www.w3.org/2000/01/rdf-schema#"+predicate))
result = []
for k in res:
result.append(k)
return result
def getAllClass(self, keywords):
key_list = []
res = self.get_subjects('equivalentClass', keywords)
while res:
tstr = res[0].split('#')
if len(tstr)>1:
key_list.append(tstr[1])
res = self.get_subClasses(tstr[1], "subClassOf")
return key_list
示例6: skosd
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def skosd(url, lang="en"):
"""
Pass in a URL (can be a file protocol) for a SKOS file and get
back a dictionary of code => values.
"""
graph = Graph()
graph.parse(url)
skos_dictionary = {}
skos_list = []
for concept in graph.subjects(RDF.type, skos.Concept):
# determine the code
code = graph.value(concept, skos.notation)
# get the preferred language label, there could be more than one
labels = list(graph.objects(concept, skos.prefLabel))
if len(labels) > 1:
for label in labels:
if label.language == lang:
break
else:
label = labels[0]
if code:
skos_dictionary[code] = label
else:
skos_list.append(label)
if len(skos_dictionary.keys()) > 0:
return skos_dictionary
return skos_list
示例7: get_all_sells
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def get_all_sells():
# [0] = url / [1] = [{producte}] / [2] = precio_total
global compres
compres = []
biggest_sell = 0
counts = []
graph_compres = Graph()
graph_compres.parse(open('../data/compres'), format='turtle')
for compraUrl in graph_compres.subjects(RDF.type, ECSDI.Compra):
sell_count = 0
single_sell = [compraUrl]
products = []
for productUrl in graph_compres.objects(subject=compraUrl, predicate=ECSDI.Productos):
sell_count += 1
products.append(graph_compres.value(subject=productUrl, predicate=ECSDI.Nombre))
single_sell.append(products)
for precio_total in graph_compres.objects(subject=compraUrl, predicate=ECSDI.Precio_total):
single_sell.append(precio_total)
compres.append(single_sell)
counts.append(sell_count)
if sell_count > biggest_sell:
biggest_sell = sell_count
return biggest_sell, counts
示例8: __load_owl
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def __load_owl(owl):
"""
:param owl:
:return:
"""
owl_g = Graph()
for f in ['turtle', 'xml']:
try:
owl_g.parse(source=StringIO.StringIO(owl), format=f)
break
except SyntaxError:
pass
if not len(owl_g):
raise VocabularyException()
try:
uri = list(owl_g.subjects(RDF.type, OWL.Ontology)).pop()
vid = [p for (p, u) in owl_g.namespaces() if uri in u and p != '']
imports = owl_g.objects(uri, OWL.imports)
if not len(vid):
vid = urlparse.urlparse(uri).path.split('/')[-1]
else:
vid = vid.pop()
return vid, uri, owl_g, imports
except IndexError:
raise VocabularyNotFound()
示例9: skosdict
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def skosdict(url, lang="en"):
"""
Pass in a URL (can be a file protocol) for a SKOS file and get
back a dictionary of code => values.
"""
graph = Graph()
graph.parse(url)
dictionary = {}
for concept in graph.subjects(RDF.type, skos.Concept):
# determine the code
code = graph.value(concept, skos.notation)
if not code:
continue
# get the preferred language label, there could be more than one
labels = list(graph.objects(concept, skos.prefLabel))
if len(labels) > 1:
for label in labels:
if label.language == lang:
break
else:
label = labels[0]
dictionary[code] = label
return dictionary
示例10: main
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def main():
graph = Graph()
graph.parse(sys.argv[1], format="n3")
if len(sys.argv) > 2:
doc = URIRef(sys.argv[2])
else:
docs = []
for c in (RIF.Document, RIF.BLDDocument,
RIF.PRDDocument, RIF.CoreDocument):
for x in graph.subjects(RDF.type, c):
docs.append(x)
if len(docs) == 1:
doc = docs[0]
elif len(docs) > 1:
print >>sys.stderr, "Input contains multiple Document nodes"
print >>sys.stderr, indent+",".join([repr(x) for x in docs])
print >>sys.stderr, "Name one on the command line to select it"
sys.exit(1)
elif len(docs) < 1:
print >>sys.stderr, "Input contains no Document nodes"
for (s,p,o) in graph:
print s,p,o
sys.exit(1)
out = sys.stdout
to_rif(out, graph, doc, root=True)
示例11: test_validation
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def test_validation(self):
def validator(graph, s):
self.assertEqual(graph, self.graph)
def validate(text, results):
res = []
for r in results:
if r['label'] != 'Hanko':
res.append(r)
return res
return validate
responses.add(responses.POST, 'http://url',
json=self.matches, status=200)
output_graph = Graph()
arpa = Arpa('http://url')
res = arpafy(self.graph, self.tprop, arpa,
source_prop=self.prop,
output_graph=output_graph,
validator=validator)
self.assertEqual(res['graph'], output_graph)
self.assertEqual(res['matches'], 1)
self.assertEqual(len(output_graph), 1)
self.assertEqual(len(set(output_graph.subjects())), 1)
示例12: extract_metadata
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def extract_metadata(self, rawhead, basefile):
metadata = util.readfile(self.store.downloaded_path(
basefile, attachment="index.rdf"))
# For some reason these RDF files might use canonical
# decomposition form (NFD) which is less optimal. Fix this.
metadata = unicodedata.normalize("NFC", metadata)
sourcegraph = Graph().parse(data=metadata)
rooturi = sourcegraph.value(predicate=RDF.type, object=BIBO.Book)
if rooturi is None:
# then just try to identify the main uri and use that
subjects = set(sourcegraph.subjects())
if len(subjects) == 1:
rooturi = next(iter(subjects))
title = sourcegraph.value(subject=rooturi, predicate=DC.title)
issued = sourcegraph.value(subject=rooturi, predicate=DC.date)
if isinstance(issued, str):
# sometimes dc:date is weird like "1976[1974]" (SOU 1974:42)
if len(issued) != 4:
self.log.warning("expected issued date as single 4-digit year, got %s" % issued)
# fall back on an approximation based on the basefile
issued = basefile.split(":")[0]
issued = Literal(util.gYear(int(issued)), datatype=XSD.gYear)
attribs = self.metadata_from_basefile(basefile)
attribs["dcterms:title"] = title
if issued:
attribs["dcterms:issued"] = issued
return attribs
示例13: post
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def post(self):
g = Graph()
g.parse(StringInputSource(self.request.body), format={
'text/n3': 'n3',
}[self.request.headers['content-type']])
for anim in g.subjects(ROOM['playback'], ROOM['start']):
startAnim(anim)
示例14: accept_callback
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def accept_callback(ch, method, properties, body):
g = Graph()
g.parse(StringIO.StringIO(body), format='turtle')
print g.serialize(format='turtle')
if len(list(g.subjects(RDF.type, CURATOR.Accepted))) == 1:
print 'Request accepted!'
else:
print 'Bad request!'
示例15: accept_callback
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import subjects [as 别名]
def accept_callback(ch, method, properties, body):
global accepted
if not accepted:
g = Graph()
g.parse(StringIO.StringIO(body), format='turtle')
if len(list(g.subjects(RDF.type, CURATOR.Accepted))) == 1:
print 'Request accepted!'
accepted = True