本文整理汇总了Python中rdflib.ConjunctiveGraph.get_context方法的典型用法代码示例。如果您正苦于以下问题:Python ConjunctiveGraph.get_context方法的具体用法?Python ConjunctiveGraph.get_context怎么用?Python ConjunctiveGraph.get_context使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.ConjunctiveGraph
的用法示例。
在下文中一共展示了ConjunctiveGraph.get_context方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_dSet_parsed_as_context_returns_results
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def test_dSet_parsed_as_context_returns_results(self):
querystr = """SELECT DISTINCT ?s FROM <http://test/> { ?s ?p ?o }"""
graph = ConjunctiveGraph()
graph.get_context(URIRef('http://test/')
).parse("http://www.w3.org/People/Berners-Lee/card.rdf")
r = graph.query(querystr, loadContexts=True)
self.assert_(len(r.bindings) is not 0)
示例2: _graphFromQuads2
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def _graphFromQuads2(q):
g = ConjunctiveGraph()
#g.addN(q) # no effect on nquad output
for s,p,o,c in q:
g.get_context(c).add((s,p,o)) # kind of works with broken rdflib nquad serializer code
#g.store.add((s,p,o), c) # no effect on nquad output
return g
示例3: test_dSet_parsed_as_URL_raises_Exception
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def test_dSet_parsed_as_URL_raises_Exception(self):
querystr = """SELECT DISTINCT ?s FROM <http://test/> { ?s ?p ?o }"""
graph = ConjunctiveGraph()
graph.get_context(URIRef("http://test/")
).parse("http://www.w3.org/People/Berners-Lee/card.rdf")
self.assertRaises((URLError, UriException),
graph.query, (querystr), loadContexts=False)
示例4: NQSink
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
class NQSink(object):
def __init__(self, graph):
# NQuads is a context-aware format.
self.graph = ConjunctiveGraph(store = graph.store)
def quad(self, s, p, o, c):
self.graph.get_context(c).add((s, p, o))
示例5: test_quad_contexts
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def test_quad_contexts():
g = ConjunctiveGraph()
a = URIRef('urn:a')
b = URIRef('urn:b')
g.get_context(a).add((a, a, a))
g.addN([(b, b, b, b)])
assert set(g) == set([(a, a, a), (b, b, b)])
for q in g.quads():
assert isinstance(q[3], Graph)
示例6: NQuadsParser
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
class NQuadsParser(NTriplesParser):
def parse(self, inputsource, sink, **kwargs):
"""Parse f as an N-Triples file."""
assert sink.store.context_aware, ("NQuadsParser must be given"
" a context aware store.")
self.sink = ConjunctiveGraph(store=sink.store, identifier=sink.identifier)
source = inputsource.getByteStream()
if not hasattr(source, 'read'):
raise ParseError("Item to parse must be a file-like object.")
source = getreader('utf-8')(source)
self.file = source
self.buffer = ''
while True:
self.line = __line = self.readline()
if self.line is None:
break
try:
self.parseline()
except ParseError as msg:
raise ParseError("Invalid line (%s):\n%r" % (msg, __line))
return self.sink
def parseline(self):
self.eat(r_wspace)
if (not self.line) or self.line.startswith(('#')):
return # The line is empty or a comment
subject = self.subject()
self.eat(r_wspace)
predicate = self.predicate()
self.eat(r_wspace)
obj = self.object()
self.eat(r_wspace)
context = self.uriref() or self.nodeid() or self.sink.identifier
self.eat(r_tail)
if self.line:
raise ParseError("Trailing garbage")
# Must have a context aware store - add on a normal Graph
# discards anything where the ctx != graph.identifier
self.sink.get_context(context).add((subject, predicate, obj))
示例7: test_nquads_default_graph
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def test_nquads_default_graph():
ds = ConjunctiveGraph()
data = """
<http://example.org/s1> <http://example.org/p1> <http://example.org/o1> .
<http://example.org/s2> <http://example.org/p2> <http://example.org/o2> .
<http://example.org/s3> <http://example.org/p3> <http://example.org/o3> <http://example.org/g3> .
"""
publicID = URIRef("http://example.org/g0")
ds.parse(data=data, format="nquads", publicID=publicID)
assert len(ds) == 3, len(g)
assert len(list(ds.contexts())) == 2, len(list(ds.contexts()))
assert len(ds.get_context(publicID)) == 2, len(ds.get_context(publicID))
示例8: _construct
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def _construct(compiler, sources, query=None):
dataset = ConjunctiveGraph()
if not isinstance(sources, list):
sources = [sources]
for sourcedfn in sources:
source = sourcedfn['source']
graph = dataset.get_context(URIRef(sourcedfn.get('dataset') or source))
if isinstance(source, (dict, list)):
context_data = sourcedfn['context']
if not isinstance(context_data, list):
context_data = compiler.load_json(context_data )['@context']
context_data = [compiler.load_json(ctx)['@context']
if isinstance(ctx, unicode) else ctx
for ctx in context_data]
to_rdf(source, graph, context_data=context_data)
elif isinstance(source, Graph):
graph += source
else:
graph += compiler.cached_rdf(source)
if not query:
return graph
with compiler.path(query).open() as fp:
result = dataset.query(fp.read())
g = Graph()
for spo in result:
g.add(spo)
return g
示例9: __store_graph
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def __store_graph(cur_g, rdf_iri_string, d_dir):
try:
res_dir, dest_file = \
find_paths(rdf_iri_string, args.base + os.sep, "https://w3id.org/oc/corpus/", 10000, 1000)
dest_dir = res_dir.replace(args.base + os.sep, d_dir + os.sep)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
cur_file = dest_file.replace(res_dir, dest_dir)
if os.path.exists(cur_file):
c_graph = __load_graph(cur_file)
else:
c_graph = ConjunctiveGraph()
c_graph.remove_context(c_graph.get_context(cur_g.identifier))
c_graph.addN([item + (cur_g.identifier,) for item in list(cur_g)])
with open(dest_file.replace(res_dir, dest_dir), "w") as f:
cur_json_ld = json.loads(c_graph.serialize(format="json-ld", context=context_json))
cur_json_ld["@context"] = context_path
json.dump(cur_json_ld, f, indent=4)
# repok.add_sentence("File '%s' added." % cur_file)
return dest_file
except Exception as e:
reperr.add_sentence("[5] It was impossible to store the RDF statements in %s. %s" %
(dest_file, str(e)))
示例10: test_bnode_publicid
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def test_bnode_publicid():
g = ConjunctiveGraph()
b = BNode()
data = '<d:d> <e:e> <f:f> .'
print("Parsing %r into %r" % (data, b))
g.parse(data=data, format='turtle', publicID=b)
triples = list(g.get_context(b).triples((None, None, None)))
if not triples:
raise Exception("No triples found in graph %r" % b)
u = URIRef(b)
triples = list(g.get_context(u).triples((None, None, None)))
if triples:
raise Exception("Bad: Found in graph %r: %r" % (u, triples))
示例11: graph
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def graph(self):
g = ConjunctiveGraph()
for prefix in self.__prefixes:
g.bind(prefix, self.__prefixes[prefix])
variables = {}
def nodify(elm):
if is_variable(elm):
if not (elm in variables):
elm_node = BNode(elm)
variables[elm] = elm_node
return variables[elm]
else:
if elm == 'a':
return RDF.type
elif elm.startswith('"'):
return Literal(elm.lstrip('"').rstrip('"'))
else:
try:
return float(elm)
except ValueError:
return URIRef(elm)
nxg = nx.Graph()
for (s, p, o) in self._tps:
nxg.add_nodes_from([s, o])
nxg.add_edge(s, o)
contexts = dict([(str(index), c) for (index, c) in enumerate(nx.connected_components(nxg))])
for (s, p, o) in self._tps:
s_node = nodify(s)
o_node = nodify(o)
p_node = nodify(p)
context = None
for uid in contexts:
if s in contexts[uid]:
context = str(uid)
g.get_context(context).add((s_node, p_node, o_node))
return g
示例12: test_serialize
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def test_serialize(self):
g=ConjunctiveGraph()
uri1=URIRef("http://example.org/mygraph1")
uri2=URIRef("http://example.org/mygraph2")
bob = URIRef(u'urn:bob')
likes = URIRef(u'urn:likes')
pizza = URIRef(u'urn:pizza')
g.get_context(uri1).add((bob, likes, pizza))
g.get_context(uri2).add((bob, likes, pizza))
s=g.serialize(format='nquads')
self.assertEqual(len([x for x in s.split(b("\n")) if x.strip()]), 2)
g2=ConjunctiveGraph()
g2.parse(data=s, format='nquads')
self.assertEqual(len(g), len(g2))
self.assertEqual(sorted(x.identifier for x in g.contexts()), sorted(x.identifier for x in g2.contexts()))
示例13: generate_config_file
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def generate_config_file(data_source, rdf_data=None, rdf_format=None, sparql_url=None, sparql_graph=None):
current_task.update_state(state='PROGRESS', meta={'progress_percent': 15, 'progress_msg': 'Reading provided RDF data...'})
try:
if data_source == 'rdf':
data_graph = Graph()
data_graph.parse(format=rdf_format, data=rdf_data)
else:
g = ConjunctiveGraph('SPARQLStore')
g.open(sparql_url)
data_graph = g.get_context(sparql_graph) if sparql_graph else g
except Exception, e:
raise Exception("An error occurred while trying to read provided data source: %s" % str(e))
示例14: get_ltw_data_graph
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
def get_ltw_data_graph(graph_id=None):
if not graph_id:
ltwapp = App.query.filter_by(id=session['app']).first()
graph_id = ltwapp.graph_id
if graph_id:
Virtuoso = plugin("Virtuoso", Store)
store = Virtuoso(app.config['VIRTUOSO_ODBC'])
ltw_data_graph = ConjunctiveGraph(store=store)
g = ltw_data_graph.get_context(graph_id)
# Initialization step needed to make Virtuoso library work
g.add((URIRef('initializationstuff'), URIRef('initializationstuff'), URIRef('initializationstuff')))
g.remove((URIRef('initializationstuff'), URIRef('initializationstuff'), URIRef('initializationstuff')))
return g
else:
return None
示例15: GraphCache
# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import get_context [as 别名]
class GraphCache(object):
def __init__(self, cachedir):
self.graph = ConjunctiveGraph()
self.mtime_map = {}
self.cachedir = cachedir
if not os.path.isdir(cachedir):
os.makedirs(cachedir)
def load(self, url):
src = VOCAB_SOURCE_MAP.get(str(url), url)
if os.path.isfile(url):
context_id = create_input_source(url).getPublicId()
last_vocab_mtime = self.mtime_map.get(url)
vocab_mtime = os.stat(url).st_mtime
if not last_vocab_mtime or last_vocab_mtime < vocab_mtime:
logger.debug("Parse file: '%s'", url)
self.mtime_map[url] = vocab_mtime
# use CG as workaround for json-ld always loading as dataset
graph = ConjunctiveGraph()
graph.parse(src, format=guess_format(src))
self.graph.remove_context(context_id)
for s, p, o in graph:
self.graph.add((s, p, o, context_id))
return graph
else:
context_id = url
if any(self.graph.triples((None, None, None), context=context_id)):
logger.debug("Using context <%s>" % context_id)
return self.graph.get_context(context_id)
cache_path = self.get_fs_path(url)
if os.path.exists(cache_path):
logger.debug("Load local copy of <%s> from '%s'", context_id, cache_path)
return self.graph.parse(cache_path, format='turtle', publicID=context_id)
else:
logger.debug("Fetching <%s> to '%s'", context_id, cache_path)
graph = self.graph.parse(src,
format='rdfa' if url.endswith('html') else None)
with open(cache_path, 'w') as f:
graph.serialize(f, format='turtle')
return graph
def get_fs_path(self, url):
return os.path.join(self.cachedir, quote(url, safe="")) + '.ttl'