本文整理汇总了Python中rdflib.Graph.resource方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.resource方法的具体用法?Python Graph.resource怎么用?Python Graph.resource使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.Graph
的用法示例。
在下文中一共展示了Graph.resource方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: LocalStore
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
class LocalStore():
'''
This class is a wrapper for the Graph class that
handles ontology binding and triples serialization.
'''
def __init__(self):
self.g = Graph()
self.ns = {}
def bind_namespaces(self, namespaces):
for ns in namespaces:
# ns is the prefix and the key
self.g.bind(ns, Namespace(namespaces[ns]))
self.ns[ns] = Namespace(namespaces[ns])
def get_namespaces(self):
ns = []
for namespace in self.g.namespaces():
ns.append(namespace)
return ns
def get_resource(self, urn):
return self.g.resource(urn)
def add_triple(self, s, v, p):
self.g.add((s, v, p))
def serialize(self, format):
return self.g.serialize(format=format)
示例2: test_parse_temporal_is_failsafe
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
def test_parse_temporal_is_failsafe(self):
node = URIRef('http://nowhere.org')
g = Graph()
g.set((node, RDF.type, DCT.PeriodOfTime))
assert temporal_from_rdf(g.resource(node)) is None
assert temporal_from_rdf(Literal('unparseable')) is None
示例3: test_parse_temporal_as_gov_uk_format
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
def test_parse_temporal_as_gov_uk_format(self):
node = URIRef('http://reference.data.gov.uk/id/year/2017')
g = Graph()
g.set((node, RDF.type, DCT.PeriodOfTime))
daterange = temporal_from_rdf(g.resource(node))
assert isinstance(daterange, db.DateRange)
assert daterange.start, date(2017, 1 == 1)
assert daterange.end, date(2017, 12 == 31)
示例4: parse_graph
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
def parse_graph(self, url, fmt):
graph = Graph(namespace_manager=namespace_manager)
graph.parse(data=requests.get(url).text, format=fmt)
for id, data in self.dcat_datasets(graph):
self.add_item(id, graph=data)
for cls, prop in KNOWN_PAGINATION:
if (None, RDF.type, cls) in graph:
pagination = graph.value(predicate=RDF.type, object=cls)
pagination = graph.resource(pagination)
next_url = url_from_rdf(pagination, prop)
if next_url:
self.parse_graph(next_url, fmt)
break
示例5: test_parse_temporal_as_schema_format
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
def test_parse_temporal_as_schema_format(self):
node = BNode()
g = Graph()
start = faker.past_date(start_date='-30d')
end = faker.future_date(end_date='+30d')
g.set((node, RDF.type, DCT.PeriodOfTime))
g.set((node, SCHEMA.startDate, Literal(start)))
g.set((node, SCHEMA.endDate, Literal(end)))
daterange = temporal_from_rdf(g.resource(node))
assert isinstance(daterange, db.DateRange)
assert daterange.start == start
assert daterange.end == end
示例6: test_can_extract_from_rdf_resource
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
def test_can_extract_from_rdf_resource(self):
node = BNode()
g = Graph()
title = faker.sentence()
url = faker.uri()
g.add((node, RDF.type, DCAT.Distribution))
g.add((node, DCT.title, Literal(title)))
g.add((node, DCAT.downloadURL, Literal(url)))
resource = resource_from_rdf(g.resource(node))
resource.validate()
assert isinstance(resource, Resource)
assert resource.title == title
assert resource.url == url
示例7: test_catalog_rdf_paginate
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
def test_catalog_rdf_paginate(self, client):
VisibleDatasetFactory.create_batch(4)
url = url_for('site.rdf_catalog_format', format='n3', page_size=3)
next_url = url_for('site.rdf_catalog_format', format='n3',
page=2, page_size=3, _external=True)
response = client.get(url)
assert200(response)
graph = Graph().parse(data=response.data, format='n3')
pagination = graph.value(predicate=RDF.type,
object=HYDRA.PartialCollectionView)
assert pagination is not None
pagination = graph.resource(pagination)
assert not pagination.value(HYDRA.previous)
assert pagination.value(HYDRA.next).identifier == URIRef(next_url)
示例8: Store
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
class Store():
'''
This class is a wrapper for the Graph class that
handles ontology binding and triples serialization.
'''
def __init__(self, endpoint=None):
if endpoint is None:
self.g = Graph()
else:
self._store = sparqlstore.SPARQLUpdateStore()
self._store.open((endpoint, endpoint))
self.g = Graph(self._store, URIRef('urn:x-arq:DefaultGraph'))
self.ns = {}
def bind_namespaces(self, namespaces):
for ns in namespaces:
# ns is the prefix and the key
self.g.bind(ns, Namespace(namespaces[ns]))
self.ns[ns] = Namespace(namespaces[ns])
def get_namespaces(self):
ns = []
for namespace in self.g.namespaces():
ns.append(namespace)
return ns
def get_resource(self, urn):
return self.g.resource(urn)
def add_triple(self, s, v, p):
self.g.add((s, v, p))
def serialize(self, format):
return self.g.serialize(format=format)
def update(self):
return self.g.update(
"INSERT DATA { %s }" % self.g.serialize(format='nt'))
示例9: temporal_from_resource
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
def temporal_from_resource(resource):
'''
Parse a temporal coverage from a RDF class/resource ie. either:
- a `dct:PeriodOfTime` with schema.org `startDate` and `endDate` properties
- an inline gov.uk Time Interval value
- an URI reference to a gov.uk Time Interval ontology
http://reference.data.gov.uk/
'''
if isinstance(resource.identifier, URIRef):
# Fetch remote ontology if necessary
g = Graph().parse(str(resource.identifier))
resource = g.resource(resource.identifier)
if resource.value(SCHEMA.startDate):
return db.DateRange(
start=resource.value(SCHEMA.startDate).toPython(),
end=resource.value(SCHEMA.endDate).toPython()
)
elif resource.value(SCV.min):
return db.DateRange(
start=resource.value(SCV.min).toPython(),
end=resource.value(SCV.max).toPython()
)
示例10: parse_graph
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
def parse_graph(self, url, fmt):
graph = Graph(namespace_manager=namespace_manager)
while url:
subgraph = Graph(namespace_manager=namespace_manager)
subgraph.parse(data=requests.get(url).text, format=fmt)
url = None
for cls, prop in KNOWN_PAGINATION:
if (None, RDF.type, cls) in subgraph:
pagination = subgraph.value(predicate=RDF.type, object=cls)
pagination = subgraph.resource(pagination)
url = url_from_rdf(pagination, prop)
break
graph += subgraph
for node in graph.subjects(RDF.type, DCAT.Dataset):
id = graph.value(node, DCT.identifier)
kwargs = {'nid': str(node)}
kwargs['type'] = 'uriref' if isinstance(node, URIRef) else 'blank'
self.add_item(id, **kwargs)
return graph
示例11: RdfGrapher
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
class RdfGrapher(object):
'''
take our json output from a preprocessor and
generate an rdf graph to serialize as json-ld or turtle?
to be decided...
'''
def __init__(self, data):
self.graph = Graph()
self._bind_namespaces()
self.data = data
def _bind_namespaces(self):
# bind our lovely namespaces
for prefix, uri in _ontology_uris.iteritems():
self.graph.bind(prefix, uri)
def _generate_predicate(self, prefix, name):
return Namespace(_ontology_uris[prefix])[name]
def _create_resource(self, resource_prefix, resource_type, identifier=''):
# make a thing with a uuid as a urn
# and just assign it to type if it's not overridden
identifier = identifier if identifier else uuid4().urn
resource = self.graph.resource(identifier)
ref = Namespace(_ontology_uris[resource_prefix])[resource_type]
resource.add(OWL.a, URIRef(ref))
return resource
def _process_catalog(self, entity):
catalog_record = self._create_resource(
'dcat', 'CatalogRecord', entity['object_id'])
self._handle_triples(
entity,
catalog_record,
[
'object_id',
'urls',
'relationships',
'datasets',
'webpages',
'services'
]
)
for url in entity.get('urls', []):
self._handle_url(url)
for webpage in entity.get('webpages', []):
self._handle_webpage(webpage)
for relationship in entity.get('relationships', []):
# so. current object, verb, id of object, existence unknown
self.relates.append(
(catalog_record, relationship['relate'],
relationship['object_id'])
)
def _handle_webpage(self, webpage):
entity = self._create_resource(
'bibo', 'WebPage', webpage.get('object_id')
)
for relationship in webpage.get('relationships', []):
self.relates.append(
(entity, relationship['relate'],
relationship['object_id'])
)
def _handle_url(self, url):
entity = self._create_resource(
'bcube', 'Url', url.get('object_id')
)
self._handle_triples(url, entity, ['object_id'])
def _handle_layer(self, layer):
entity = self._create_resource(
"bcube", 'Layer', layer.get('object_id')
)
self._handle_triples(layer, entity, ['object_id', 'relationships'])
for relationship in layer.get('relationships', []):
self.relates.append(
(entity, relationship['relate'], relationship['object_id']))
def _handle_triples(self, entity, thing, excludes):
# today in badly named things, entity is the
# json blob, thing is the parent rdf object
for pred, val in entity.iteritems():
if pred in excludes:
continue
if not val:
continue
prefix, name = pred.split(':')
val = [val] if not isinstance(val, list) else val
for v in val:
if name in [
'westBound', 'eastBound', 'northBound', 'southBound']:
#.........这里部分代码省略.........
示例12: test_suite
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
doap:programming-language "Python" ;
doap:title "RDFLib plugin for JSON-LD " .
""".format(**vars()), format='turtle')
if asserter_name:
graph.add((asserter, RDF.type, FOAF.Person))
graph.add((asserter, FOAF.name, asserter_name))
graph.add((rdflib_jsonld, DOAP.developer, asserter))
for args in test_suite(skip_known_bugs=False):
try:
args[0](*args[1:])
success = True
except AssertionError:
success = False
assertion = graph.resource(BNode())
assertion.add(RDF.type, EARL.Assertion)
assertion.add(EARL.mode, EARL.automatic)
if asserter:
assertion.add(EARL.assertedBy, asserter)
assertion.add(EARL.subject, rdflib_jsonld)
assertion.add(EARL.test, URIRef(
"http://json-ld.org/test-suite/tests/{1}-manifest.jsonld#t{2}".format(*args)))
result = graph.resource(BNode())
assertion.add(EARL.result, result)
result.add(RDF.type, EARL.TestResult)
result.add(DC.date, Literal(datetime.utcnow()))
result.add(EARL.outcome, EARL.passed if success else EARL.failed)
graph.serialize(sys.stdout, format='turtle')
示例13: Graph
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
"""
RDFLib has a Resource class, for a resource-centric API
"""
from rdflib import Graph, RDF, RDFS, Literal
from rdflib.namespace import FOAF
g = Graph()
bob = g.resource('urn:bob')
bob.set(RDF.type, FOAF.Person) # .set replaces all other values
bob.set(FOAF.name, Literal("Bob"))
bill = g.resource('urn:bill')
bill.add(RDF.type, FOAF.Person) # add adds to existing values
bill.add(RDF.type, FOAF.Agent)
bill.set(RDFS.label, Literal("Bill"))
bill.add(FOAF.knows, bob)
# Resources returned when querying are 'auto-boxed' as resources:
print "Bill's friend: ", bill.value(FOAF.knows).value(FOAF.name)
# slicing ([] syntax) can also be used:
示例14: extract_metadata_register
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
#.........这里部分代码省略.........
elif key == 'Rubrik':
# Change acts to Balkar never contain the SFS no
# of the Balk.
if basefile not in val and not val.endswith("balken"):
self.log.warning(
"%s: Base SFS %s not in title %r" % (basefile,
basefile,
val))
d[docuri]["dcterms:title"] = val
d[docuri]["rdf:type"] = self._forfattningstyp(val)
elif key == 'Observera':
if not self.config.keepexpired:
if 'Författningen är upphävd/skall upphävas: ' in val:
dateval = datetime.strptime(val[41:51], '%Y-%m-%d')
if dateval < datetime.today():
raise UpphavdForfattning("%s is an expired SFS"
% basefile,
dummyfile=self.store.parsed_path(basefile))
d[docuri]["rdfs:comment"] = val
elif key == 'Ikraft':
d[docuri]["rpubl:ikrafttradandedatum"] = val[:10]
elif key == 'Omfattning':
# First, create rdf statements for every
# single modified section we can find
for changecat in val.split('; '):
if (changecat.startswith('ändr.') or
changecat.startswith('ändr ') or
changecat.startswith('ändring ')):
pred = self.ns['rpubl'].ersatter
elif (changecat.startswith('upph.') or
changecat.startswith('upp.') or
changecat.startswith('utgår')):
pred = self.ns['rpubl'].upphaver
elif (changecat.startswith('ny') or
changecat.startswith('ikrafttr.') or
changecat.startswith('ikrafftr.') or
changecat.startswith('ikraftr.') or
changecat.startswith('ikraftträd.') or
changecat.startswith('tillägg')):
pred = self.ns['rpubl'].inforsI
elif (changecat.startswith('nuvarande') or
changecat.startswith('rubr. närmast') or
changecat in ('begr. giltighet', 'Omtryck',
'omtryck', 'forts.giltighet',
'forts. giltighet',
'forts. giltighet av vissa best.')):
# some of these changecats are renames, eg
# "nuvarande 2, 3, 4, 5 §§ betecknas 10,
# 11, 12, 13, 14, 15 §§;" or
# "rubr. närmast efter 1 § sätts närmast
# före 10 §"
pred = None
else:
self.log.warning(
"%s: Okänd omfattningstyp %r" %
(basefile, changecat))
pred = None
old_currenturl = self.lagrum_parser._currenturl
self.lagrum_parser._currenturl = docuri
for node in self.lagrum_parser.parse_string(changecat,
pred):
if hasattr(node, 'predicate'):
qname = g.qname(node.predicate)
d[docuri][qname] = node.uri
self.lagrum_parser._currenturl = old_currenturl
# Secondly, preserve the entire text
d[docuri]["rpubl:andrar"] = val
elif key == 'Förarbeten':
for node in self.forarbete_parser.parse_string(val,
"rpubl:forarbete"):
if hasattr(node, 'uri'):
if "rpubl:forarbete" not in d[docuri]:
d[docuri]["rpubl:forarbete"] = []
d[docuri]["rpubl:forarbete"].append(node.uri)
d[node.uri] = {"dcterms:identifier": str(node)}
elif key == 'CELEX-nr':
for celex in re.findall('3\d{2,4}[LR]\d{4}', val):
b = BNode()
cg = Graph()
cg.add((b, RPUBL.celexNummer, Literal(celex)))
celexuri = self.minter.space.coin_uri(cg.resource(b))
if "rpubl:genomforDirektiv" not in d[docuri]:
d[docuri]["rpubl:genomforDirektiv"] = []
d[docuri]["rpubl:genomforDirektiv"].append(celexuri)
d[celexuri] = {"rpubl:celexNummer": celex}
elif key == 'Tidsbegränsad':
d["rinfoex:tidsbegransad"] = val[:10]
expdate = datetime.strptime(val[:10], '%Y-%m-%d')
if expdate < datetime.today():
if not self.config.keepexpired:
raise UpphavdForfattning(
"%s is expired (time-limited) SFS" % basefile,
dummyfile=self.store.parsed_path(basefile))
else:
self.log.warning(
'%s: Obekant nyckel [\'%s\']' % basefile, key)
utfardandedatum = self._find_utfardandedatum(sfsnr)
if utfardandedatum:
d[docuri]["rpubl:utfardandedatum"] = utfardandedatum
return d
示例15: Namespace
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import resource [as 别名]
SCHEMA = Namespace("http://schema.org/")
VANN = Namespace("http://purl.org/vocab/vann/")
#BF = Namespace("http://bibframe.org/vocab/")
LF = Namespace("http://purl.org/net/927/libframe#")
LTAX = Namespace("http://purl.org/net/927/libframe/taxonomy#")
DOMAIN = SCHEMA.domain
graph = Graph()
for key, obj in vars().items():
if isinstance(obj, Namespace):
graph.namespace_manager.bind(key.lower(), obj)
graph.namespace_manager.bind(None, LF)
graph.resource(LF.Work).add(RDF.type, OWL.Class)
graph.resource(LF.Instance).add(RDF.type, OWL.Class)
def vocab_from_marcmap(marcmap):
bib = marcmap['bib']
process_leader(bib)
process_fix_media_types(bib, '008')
process_fix_media_types(bib, '006')
process_fix_media_types(bib, '007')
_fixed_cleanup()
for tag, tagdef in bib.items():
if tag in ('000', '006', '007', '008', 'fixprops'):
continue
process_tag(tag, tagdef)
_cleanup()