本文整理汇总了Python中rdflib.Graph.objects方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.objects方法的具体用法?Python Graph.objects怎么用?Python Graph.objects使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.Graph
的用法示例。
在下文中一共展示了Graph.objects方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: prepareSellResponse
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [as 别名]
def prepareSellResponse(urlSend):
g = Graph()
enviaments = Graph()
enviaments.parse(open('../data/enviaments'), format='turtle')
urlProducts = []
for item in enviaments.objects(subject=urlSend, predicate=ECSDI.Envia):
for product in enviaments.objects(subject=item, predicate=ECSDI.productos):
urlProducts.append(product)
products = Graph()
products.parse(open('../data/productes'), format='turtle')
for item in urlProducts:
marca = products.value(subject=item, predicate=ECSDI.Marca)
modelo = products.value(subject=item, predicate=ECSDI.Modelo)
nombre = products.value(subject=item, predicate=ECSDI.Nombre)
precio = products.value(subject=item, predicate=ECSDI.Precio)
g.add((item, RDF.type, ECSDI.Producto))
g.add((item, ECSDI.Marca, Literal(marca, datatype=XSD.string)))
g.add((item, ECSDI.Modelo, Literal(modelo, datatype=XSD.string)))
g.add((item, ECSDI.Precio, Literal(precio, datatype=XSD.float)))
g.add((item, ECSDI.Nombre, Literal(nombre, datatype=XSD.string)))
return g
示例2: get_all_sells
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [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
示例3: test__dataset__add_proxy_resource_uris_to_graph
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [as 别名]
def test__dataset__add_proxy_resource_uris_to_graph():
sample_url = "http://purl.org/dc/elements/1.1/subject"
ds = DataSet.objects.create(**ds_fields)
assert ds
proxy_field = ds.generate_proxyfield_uri("Sjoerd, Siebinga", language="nl")
assert proxy_field.endswith("/resource/dataset/afrikamuseum/nl/Sjoerd,_Siebinga")
proxy_field = ds.generate_proxyfield_uri("Sjoerd, Siebinga", language=None)
assert proxy_field.endswith("/resource/dataset/afrikamuseum/Sjoerd,_Siebinga")
graph = Graph(identifier="http://acc.dcn.delving.org/resource/aggregation/afrikamuseum/100-1")
graph.namespace_manager = lod.namespace_manager
graph.parse(data=test_graph, format='xml')
assert graph
assert len(list(graph.objects(predicate=URIRef(sample_url)))) == 3
assert all(isinstance(obj, Literal) for obj in graph.objects(predicate=URIRef(sample_url)))
new_graph, converted_literals = ds.update_graph_with_proxy_field(graph, sample_url)
assert new_graph
assert converted_literals
assert all(isinstance(obj, URIRef) for obj in new_graph.objects(predicate=URIRef(sample_url)))
assert len(converted_literals) == 3
coined_uri, obj = sorted(converted_literals)[0]
assert coined_uri.endswith('/resource/dataset/afrikamuseum/beelden')
assert obj.value == 'beelden'
示例4: makeBots
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [as 别名]
def makeBots(application, configFilename):
bots = {}
g = Graph()
g.parse(configFilename, format='n3')
for botNode, botJid, password, name, birthdate in g.query("""
SELECT DISTINCT ?botNode ?botJid ?password ?name ?birthdate WHERE {
?botNode a db:DiaryBot;
rdfs:label ?name;
foaf:jabberID ?botJid .
OPTIONAL {
?botNode db:password ?password .
}
OPTIONAL {
?botNode bio:event [ a bio:Birth; bio:date ?birthdate ] .
}
}""", initNs=INIT_NS):
if birthdate is not None:
birthdate = parse(birthdate).replace(tzinfo=tz.gettz('UTC'))
b = Bot(str(name), botJid, password,
set(g.objects(botNode, DB['owner'])),
birthdate=birthdate,
autotexts=list(map(unicode, g.objects(botNode, DB['autotext'])))
)
if hasattr(b, 'client'):
b.client.setServiceParent(application)
bots[str(name)] = b
for s,p,o in g.triples((None, FOAF['jabberID'], None)):
_agent[str(o)] = s
for s,p,o in g.triples((None, FOAF['name'], None)):
_foafName[s] = o
return bots
示例5: local_or_remote_reverse
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [as 别名]
def local_or_remote_reverse(self, g, rdfPred, djField, datatype=None, lang=None):
uri = lambda x: x.uri
# lets try the local version
self.base_single_reverse(uri, g, rdfPred, djField, datatype, lang)
if not getattr(self, djField):
self.base_single_reverse(uri, g, rdfPred, "remote_" + djField + "_uri", datatype, lang, empty_value=u"")
# to get the label... it is more complicated
value = list(g.objects(URIRef(uri(self)), rdfPred))
if len(value) == 1:
value = value[0] # Should be an URIRef
if isinstance(value, URIRef):
# Il faut parsser sur la PES a cause des roles
g_value = Graph()
imp_uri = "%s/get_rdf/?url=%s" % (
settings.PES_HOST,
urllib.quote_plus(unicode(value).encode("utf-8")),
)
g_value.parse(imp_uri, format="json-ld")
labels = list(g_value.objects(value, settings.NS.rdfs.label))
labels = set(select_with_lang(labels, lang))
if len(labels) > 0:
label = labels.pop() # On suppose tres fort qu'il y en qu'un
else:
# lets try skos:prefLabel
labels = list(g_value.objects(value, settings.NS.skos.prefLabel))
labels = set(select_with_lang(labels, lang))
if len(labels) > 0:
label = labels.pop()
else:
label = u""
setattr(self, "remote_" + djField + "_label", unicode(label))
else:
pass
else: # I dont know what to do
pass
示例6: check_ro
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [as 别名]
def check_ro(self):
manifest_file = os.path.join(self.folder, "metadata", "manifest.json")
self.assertTrue(os.path.isfile(manifest_file), "Can't find " + manifest_file)
arcp_root = self.find_arcp()
base = urllib.parse.urljoin(arcp_root, "metadata/manifest.json")
g = Graph()
with open(manifest_file, "rb") as f:
# Note: This will use https://w3id.org/bundle/context
g.parse(file=f, format="json-ld", publicID=base)
print("Parsed manifest:\n\n")
g.serialize(sys.stdout, format="nt")
ro = None
for ro in g.subjects(ORE.isDescribedBy, URIRef(base)):
break
self.assertTrue(ro, "Can't find RO with ore:isDescribedBy")
profile = None
for dc in g.objects(ro, DCTERMS.conformsTo):
profile = dc
break
self.assertTrue(profile, "Can't find profile with dct:conformsTo")
self.assertEquals(profile, URIRef("https://w3id.org/cwl/prov/0.3.0"),
"Unexpected cwlprov version " + profile)
paths = []
externals = []
for aggregate in g.objects(ro, ORE.aggregates):
print(aggregate)
if not arcp.is_arcp_uri(aggregate):
externals.append(aggregate)
# Won't check external URIs existence here
# TODO: Check they are not relative!
continue
# arcp URIs - assume they are local to our RO
path = arcp.parse_arcp(aggregate).path[1:] # Strip first /
paths.append(path)
# Convert to local path, in case it uses \ on Windows
lpath = provenance._convert_path(path, posixpath, os.path)
lfile = os.path.join(self.folder, lpath)
self.assertTrue(os.path.isfile(lfile), "Can't find aggregated " + lfile)
self.assertTrue(paths, "Didn't find any arcp aggregates")
self.assertTrue(externals, "Didn't find any data URIs")
for ext in ["provn", "xml", "json", "jsonld", "nt", "ttl"]:
f = "metadata/provenance/primary.cwlprov.%s" % ext
self.assertTrue(f in paths, "provenance file missing " + f)
for f in ["workflow/primary-job.json", "workflow/packed.cwl"]:
self.assertTrue(f in paths, "workflow file missing " + f)
示例7: __load_owl
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [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()
示例8: skosdict
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [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
示例9: parse
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [as 别名]
def parse(self):
if "workflowBundle.ttl" in self.zip.namelist():
format = "n3"
rootfile = "workflowBundle.ttl"
elif "workflowBundle.rdf" in self.zip.namelist():
rootfile = "workflowBundle.rdf"
format = "xml"
else:
raise Scufl2Error("Can't find workflowBundle.ttl or "
"workflowBundle.rdf")
self.uri = "file://" + urllib.pathname2url(os.path.abspath(self.filename)) + "/"
early_graph = Graph()
rdf_file = self.zip.open(rootfile)
early_graph.parse(rdf_file, self.uri, format=format)
sameBaseAs = list(early_graph.objects(subject=URIRef(self.uri), predicate=Scufl2NS.sameBaseAs))
if not sameBaseAs:
# Fall back to the file:/// URIs
self.graph = early_graph
else:
# Use the sameBaseAs as the base
self.uri = sameBaseAs[0]
self.graph = Graph()
# Reparse it
rdf_file = self.zip.open(rootfile)
self.graph.parse(rdf_file, self.uri, format=format)
self.parse_all_graphs(self.uri)
示例10: __init__
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [as 别名]
def __init__(self, root_uri, store, create=False):
"""I override `Service.__init__` to update the built-in methods.
:param root_uri: the URI of this kTBS
:param store: the rdflib store containing this kTBS data
:param create: whether the store should be initialized with fresh data
NB: built-in methods may change from one execution to another, so
they have to be checked against the store.
"""
classes = [ Base,
ComputedTrace,
ComputedTraceObsels,
KtbsRoot,
Method,
StoredTrace,
StoredTraceObsels,
TraceModel,
]
init_with = create and self.init_ktbs
Service.__init__(self, root_uri, store, classes, init_with)
# testing that all built-in methods are still supported
graph = Graph(self.store, self.root_uri)
for uri in graph.objects(self.root_uri, KTBS.hasBuiltinMethod):
if not get_builtin_method_impl(uri):
raise Exception("No implementation for built-in method <%s>"
% uri)
示例11: test_eq_diff1
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [as 别名]
def test_eq_diff1():
"""
Test eq-diff1 rule for OWL 2 RL.
If::
T(?x, owl:sameAs, ?y)
T(?x, owl:differentFrom, ?y)
then::
false
"""
g = Graph()
x = T.x
y = T.y
g.add((x, OWL.sameAs, y))
g.add((x, OWL.differentFrom, y))
owlrl.DeductiveClosure(owlrl.OWLRL_Semantics).expand(g)
result = g.objects(predicate=DAML.error)
expected = Literal(
'\'sameAs\' and \'differentFrom\' cannot be used on the same' \
+ ' subject-object pair:'
)
# expect multiple error messages for pairs (x, y), (x, x) and (y, y)
# due to contradiction:
#
# x == y and x != y => x != x and y != y and x == x and y == y
assert all(r.startswith(expected) for r in result)
示例12: __init__
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [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
示例13: obtainTotalWeight
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [as 别名]
def obtainTotalWeight(urlSend):
totalWeight = 0.0
gSends = Graph()
gSends.parse(open('../data/enviaments'), format='turtle')
productsArray = []
for lote in gSends.objects(subject=urlSend, predicate=ECSDI.Envia):
for producto in gSends.objects(subject=lote, predicate=ECSDI.productos):
productsArray.append(producto)
gProducts = Graph()
gProducts.parse(open('../data/productes'), format='turtle')
for item in productsArray:
totalWeight += float(gProducts.value(subject=item, predicate=ECSDI.Peso))
return totalWeight
示例14: skosd
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [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
示例15: factory
# 需要导入模块: from rdflib import Graph [as 别名]
# 或者: from rdflib.Graph import objects [as 别名]
def factory(cls, uri, _rdf_type=None, _no_spawn=False):
"""I implement :meth:`.interface.IResource.factory`.
Note that I implement it as a class method, so a first resource can be
created from its URI without prior knowledge with::
res = HttpResource.factory(uri)
Note also that `_rdf_type` is ignored.
:rtype: :class:`HttpResource` or :class:`~.hosted.HostedResource`
NB: if uri contains a fragment-id, the returned resource will be a
`~.hosted.HostedResource`:class: hosted by a `HttpResource`:class: .
"""
uri = coerce_to_uri(uri)
resource = _RESOURCE_CACHE.get(uri)
if resource is None and not _no_spawn:
graph = types = py_class = None
try:
graph = Graph(ProxyStore(identifier=uri), identifier=uri)
types = list(graph.objects(uri, RDF.type))
except ResourceAccessError:
return None
if _rdf_type is not None and _rdf_type not in types:
types.append(_rdf_type)
py_class = get_subclass(HttpResource, types)
# use HttpResource above and *not* cls, as cls may already
# be a class produced by get_subclass
resource = py_class(uri, graph)
_RESOURCE_CACHE[uri] = resource
return resource