本文整理汇总了Python中rdflib.graph.Graph.triples方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.triples方法的具体用法?Python Graph.triples怎么用?Python Graph.triples使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.graph.Graph
的用法示例。
在下文中一共展示了Graph.triples方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_06_retract
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
def test_06_retract(self):
graph = Graph("SWIStore", identifier="test")
graph.open("test.db")
ntriples = len(list(graph.triples((None, RDFS.label, None))))
assert ntriples > 0
graph.remove((None, RDFS.label, None))
ntriples = len(list(graph.triples((None, RDFS.label, None))))
assert ntriples == 0
graph.store.unload(graph)
graph.close()
示例2: TestSPARQLToldBNodes
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
class TestSPARQLToldBNodes(unittest.TestCase):
manual = True
def setUp(self):
NS = u"http://example.org/"
self.graph = Graph(store)
self.graph.parse(
StringInputSource(
"""
@prefix : <http://example.org/> .
@prefix rdf: <%s> .
@prefix rdfs: <%s> .
[ :prop :val ].
[ a rdfs:Class ]."""
% (RDF, RDFS)
),
format="n3",
)
def testToldBNode(self):
for s, p, o in self.graph.triples((None, RDF.type, None)):
pass
query = """SELECT ?obj WHERE { %s ?prop ?obj }""" % s.n3()
print query
rt = self.graph.query(query, DEBUG=debug)
self.failUnless(len(rt) == 1, "BGP should only match the 'told' BNode by name (result set size: %s)" % len(rt))
bindings = {Variable("subj"): s}
query = """SELECT ?obj WHERE { ?subj ?prop ?obj }"""
print query
rt = self.graph.query(query, initBindings=bindings, DEBUG=debug)
self.failUnless(
len(rt) == 1,
"BGP should only match the 'told' BNode by name (result set size: %s, BNode: %s)" % (len(rt), s.n3()),
)
def testFilterBNode(self):
for s, p, o in self.graph.triples((None, RDF.type, None)):
pass
query2 = """SELECT ?subj WHERE { ?subj ?prop ?obj FILTER( ?subj != %s ) }""" % s.n3()
print query2
rt = self.graph.query(query2, DEBUG=True)
self.failUnless(
len(rt) == 1,
"FILTER should exclude 'told' BNodes by name (result set size: %s, BNode excluded: %s)" % (len(rt), s.n3()),
)
def tearDown(self):
self.graph.store.rollback()
示例3: test_03_load
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
def test_03_load(self):
graph = Graph("SWIStore", identifier="test")
graph.store.load(cofog_test, graph)
for i, statement in enumerate(graph.triples((None, RDFS.label, None))):
for n in statement:
assert isinstance(n, Node)
assert i == 572
示例4: test_02_query
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
def test_02_query(self):
graph = Graph("SWIStore", identifier="test")
for i, statement in enumerate(graph.triples((None, RDFS.label, None))):
for n in statement:
assert isinstance(n, Node)
assert i == 572
graph.store.unload(graph)
示例5: test_collection_with_duplicates
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
def test_collection_with_duplicates():
g = Graph().parse(data=ttl, format="turtle")
for _,_,o in g.triples((URIRef("http://example.org/s"), URIRef("http://example.org/p"), None)):
break
c = g.collection(o)
assert list(c) == list(URIRef("http://example.org/" + x) for x in ["a", "b", "a"])
assert len(c) == 3
示例6: PychinkoTestCase
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
class PychinkoTestCase(unittest.TestCase):
backend = "default"
tmppath = None
def setUp(self):
self.g = Graph(store=self.backend)
self.tmppath = mkdtemp()
self.g.open(configuration=self.tmppath)
self.g.parse("test/a.n3", format="n3")
def tearDown(self):
self.g.close()
shutil.rmtree(tmppath)
def testPychinko(self):
rules = []
for s, p, o in self.g.triples((None, LOG.implies, None)):
lhs = list(patterns(s))
rhs = list(patterns(o))
rules.append(terms.Rule(lhs, rhs, (s, p, o)))
interp = Interpreter(rules)
f = Graph()
f.parse("http://eikeon.com/")
source = f
source = self.g
interp.addFacts(set(facts(source)), initialSet=True)
interp.run()
示例7: harvest_collection
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
def harvest_collection(col_url, col_uri, store_host, manifest_file=None):
store_host = clean_store_host(store_host)
with transaction.commit_on_success():
col_g = Graph(store=rdfstore(), identifier=URIRef(col_uri))
collection.fetch_and_parse(col_url, col_g, manifest_file=manifest_file)
localize_describes(store_host, col_uri, col_url, col_g)
res_uris_urls = collection.aggregated_uris_urls(col_uri, col_g)
for res_uri, res_url in res_uris_urls:
res_g = Graph(store=rdfstore(), identifier=URIRef(res_uri))
collection.fetch_and_parse(res_url, res_g)
for pred in col_res_attributes:
for t in res_g.triples((res_uri, pred, None)):
col_g.add(t)
aggr_uris_urls = collection.aggregated_uris_urls(res_uri, res_g)
for aggr_uri, aggr_url in aggr_uris_urls:
if aggr_url:
collection.fetch_and_parse(aggr_url, res_g)
localize_describes(store_host, aggr_uri, aggr_url, res_g)
localize_describes(store_host, aggr_uri, aggr_url, col_g)
seq_uris_urls = collection.aggregated_seq_uris_urls(res_uri, res_g)
for seq_uri, seq_url in seq_uris_urls:
page_uris_urls = collection.aggregated_uris_urls(seq_uri, res_g)
for page_uri, page_url in page_uris_urls:
localize_describes(store_host, page_uri, page_url, res_g)
localize_describes(store_host, res_uri, res_url, res_g)
localize_describes(store_host, res_uri, res_url, col_g)
示例8: NonEqualityPredicatesTestSuite
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
class NonEqualityPredicatesTestSuite(unittest.TestCase):
def setUp(self):
from FuXi.Rete.RuleStore import N3RuleStore
from FuXi.Rete import ReteNetwork
from FuXi.Rete.Util import generateTokenSet
self.testGraph = Graph()
self.ruleStore = N3RuleStore()
self.ruleGraph = Graph(self.ruleStore)
self.ruleGraph.parse(StringIO(testN3), format='n3')
self.testGraph.parse(StringIO(testN3), format='n3')
self.closureDeltaGraph = Graph()
self.network = ReteNetwork(
self.ruleStore,
initialWorkingMemory=generateTokenSet(self.testGraph),
inferredTarget=self.closureDeltaGraph,
nsMap={})
def testParseBuiltIns(self):
# from FuXi.Rete.RuleStore import N3Builtin
from FuXi.Rete.AlphaNode import BuiltInAlphaNode
self.failUnless(self.ruleStore.rules > 0,
"No rules parsed out from N3.")
for alphaNode in self.network.alphaNodes:
if isinstance(alphaNode, BuiltInAlphaNode):
self.failUnless(alphaNode.n3builtin.uri == MATH_NS.greaterThan,
"Unable to find math:greaterThan func")
def testEvaluateBuiltIns(self):
# from FuXi.Rete.RuleStore import N3Builtin
# from FuXi.Rete.AlphaNode import BuiltInAlphaNode
self.failUnless(first(
self.closureDeltaGraph.triples(
(None, URIRef('http://test/pred1'), Literal(3)))),
"Missing inferred :pred1 assertions")
示例9: things_from_graph
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
def things_from_graph(graph, subclasses, conceptscheme, **kwargs):
s = kwargs.get('session', requests.Session())
graph = graph
clist = []
concept_graph = Graph()
collection_graph = Graph()
for sc in subclasses.get_subclasses(SKOS.Concept):
concept_graph += graph.triples((None, RDF.type, sc))
for sc in subclasses.get_subclasses(SKOS.Collection):
collection_graph += graph.triples((None, RDF.type, sc))
for sub, pred, obj in concept_graph.triples((None, RDF.type, None)):
uri = str(sub)
matches = {}
for k in Concept.matchtypes:
matches[k] = _create_from_subject_predicate(graph, sub, URIRef(SKOS + k + 'Match'))
con = Concept(
uri_to_id(uri),
uri=uri,
concept_scheme = conceptscheme,
labels = _create_from_subject_typelist(graph, sub, Label.valid_types),
notes = _create_from_subject_typelist(graph, sub, hierarchy_notetypes(Note.valid_types)),
sources = [],
broader = _create_from_subject_predicate(graph, sub, SKOS.broader),
narrower = _create_from_subject_predicate(graph, sub, SKOS.narrower),
related = _create_from_subject_predicate(graph, sub, SKOS.related),
subordinate_arrays = _create_from_subject_predicate(graph, sub, ISO.subordinateArray),
matches=matches
)
clist.append(con)
for sub, pred, obj in collection_graph.triples((None, RDF.type, None)):
uri = str(sub)
col = Collection(
uri_to_id(uri),
uri=uri,
concept_scheme = conceptscheme,
labels = _create_from_subject_typelist(graph, sub, Label.valid_types),
notes = _create_from_subject_typelist(graph, sub, hierarchy_notetypes(Note.valid_types)),
sources = [],
members = _create_from_subject_predicate(graph, sub, SKOS.member),
superordinates = _get_super_ordinates(conceptscheme, sub, session=s)
)
clist.append(col)
return clist
示例10: test_08_n3
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
def test_08_n3(self):
st = SWIStore()
g = Graph(st, identifier="test")
st.remove((None,None,None))
g.parse(entail_test, format="n3")
st.compile()
st.entailment = "n3"
assert len(list(g.triples((None, None, None)))) == 2
st.remove((None,None,None))
示例11: bfp
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
def bfp(defaultDerivedPreds, options, factGraph, ruleSet, network,
hybridPredicates):
topDownDPreds = defaultDerivedPreds
if options.builtinTemplates:
builtinTemplateGraph = Graph().parse(options.builtinTemplates,
format='n3')
builtinDict = dict([
(pred, template) for pred, _ignore, template in
builtinTemplateGraph.triples(
(None, TEMPLATES.filterTemplate, None))])
else:
builtinDict = None
topDownStore = TopDownSPARQLEntailingStore(
factGraph.store,
factGraph,
idb=ruleSet,
DEBUG=options.debug,
derivedPredicates=topDownDPreds,
templateMap=builtinDict,
nsBindings=network.nsMap,
identifyHybridPredicates=options.hybrid,
hybridPredicates=hybridPredicates)
targetGraph = Graph(topDownStore)
for pref, nsUri in list(network.nsMap.items()):
targetGraph.bind(pref, nsUri)
start = time.time()
sTime = time.time() - start
result = targetGraph.query(options.why, initNs=network.nsMap)
if result.askAnswer:
sTime = time.time() - start
if sTime > 1:
sTimeStr = "%s seconds" % sTime
else:
sTime = sTime * 1000
sTimeStr = "%s milli seconds" % sTime
print("Time to reach answer ground goal answer of %s: %s" % (
result.askAnswer[0], sTimeStr))
else:
for rt in result:
sTime = time.time() - start
if sTime > 1:
sTimeStr = "%s seconds" % sTime
else:
sTime = sTime * 1000
sTimeStr = "%s milli seconds" % sTime
if options.firstAnswer:
break
print("Time to reach answer %s via top-down SPARQL"
" sip strategy: %s" % (rt, sTimeStr))
if options.output == 'conflict' and options.method == 'bfp':
for _network, _goal in topDownStore.queryNetworks:
print(network, _goal)
_network.reportConflictSet(options.debug)
for query in topDownStore.edbQueries:
print(query.asSPARQL())
示例12: testSerialize
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
def testSerialize(self):
s1 = URIRef('store:1')
r1 = URIRef('resource:1')
r2 = URIRef('resource:2')
label = URIRef('predicate:label')
g1 = Graph(identifier = s1)
g1.add((r1, label, Literal("label 1", lang="en")))
g1.add((r1, label, Literal("label 2")))
s2 = URIRef('store:2')
g2 = Graph(identifier = s2)
g2.add((r2, label, Literal("label 3")))
g = ConjunctiveGraph()
for s,p,o in g1.triples((None, None, None)):
g.addN([(s,p,o,g1)])
for s,p,o in g2.triples((None, None, None)):
g.addN([(s,p,o,g2)])
r3 = URIRef('resource:3')
g.add((r3, label, Literal(4)))
r = g.serialize(format='trix')
g3 = ConjunctiveGraph()
from StringIO import StringIO
g3.parse(StringIO(r), format='trix')
for q in g3.quads((None,None,None)):
# TODO: Fix once getGraph/getContext is in conjunctive graph
if isinstance(q[3].identifier, URIRef):
tg=Graph(store=g.store, identifier=q[3].identifier)
else:
# BNode, this is a bit ugly
# we cannot match the bnode to the right graph automagically
# here I know there is only one anonymous graph,
# and that is the default one, but this is not always the case
tg=g.default_context
self.assertTrue(q[0:3] in tg)
示例13: prepare
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
def prepare(self):
logger.info('Building RDF graph')
graph = Graph()
for inc in self.include:
lg0 = len(graph)
graph.load(inc, format=self.extFromFilename(inc))
logger.info(' - Included {} triples from {}'.format(len(graph) - lg0, inc))
try:
scheme_uri = next(graph.triples((None, RDF.type, SKOS.ConceptScheme)))
except StopIteration:
raise Exception('Concept scheme URI could not be found in vocabulary scheme data')
scheme_uri = scheme_uri[0]
now = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
graph.set((URIRef(scheme_uri), DCTERMS.modified, Literal(now, datatype=XSD.dateTime)))
lg0 = len(graph)
for resource in self.vocabulary.resources:
self.convert_resource(graph, resource, self.vocabulary.resources, scheme_uri,
self.vocabulary.default_language.alpha2)
logger.info(' - Added {} triples'.format(len(graph) - lg0))
all_concepts = set([tr[0] for tr in graph.triples((None, RDF.type, SKOS.Concept))])
for inc in self.mappings_from:
lg0 = len(graph)
mappings = self.load_mappings(inc)
for tr in mappings.triples((None, None, None)):
if tr[0] in all_concepts:
graph.add(tr)
logger.info(' - Added {} mappings from {}'.format(len(graph) - lg0, inc))
logger.info('Skosify...')
self.skosify_process(graph)
return {'graph': graph}
示例14: remove_project_text
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
def remove_project_text(project_uri, text_uri):
# Correctly format project uri and get project graph
project_uri = uris.uri('semantic_store_projects', uri=project_uri)
project_g = Graph(rdfstore(), identifier=project_uri)
project_metadata_g = Graph(rdfstore(), identifier=uris.project_metadata_graph_identifier(p_uri))
# Make text uri a URIRef (so Graph will understand)
text_uri = URIRef(text_uri)
with transaction.commit_on_success():
for t in specific_resources_subgraph(project_g, text_uri, project_uri):
project_g.remove(t)
for t in project_g.triples((text_uri, None, None)):
# Delete triple about text from project graph
project_g.remove(t)
project_metadata_g.remove(t)
project_g.remove((URIRef(project_uri), NS.ore.aggregates, text_uri))
for text in Text.objects.filter(identifier=text_uri, valid=True).only('valid'):
text.valid = False
text.save()
示例15: rdf2dendropyTree
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import triples [as 别名]
def rdf2dendropyTree(filepath):
from rdflib.graph import Graph
from dendropy import Node, Tree, Edge, TaxonSet, Taxon
graph = Graph()
graph.parse(filepath)
nd_dict = {}
has_parent_predicate = OBO_PREFIX + HAS_PARENT_PREDICATE
if _DEBUGGING:
out = open("parse_rdf.txt", "w")
taxon_set = TaxonSet()
OBO = Namespace(u"http://purl.obolibrary.org/obo/")
parentless = set()
for s, p, o in graph.triples((None, OBO[HAS_PARENT_PREDICATE], None)):
parent = nd_dict.get(id(o))
if parent is None:
# print 'Parent o.value = ', o.value(rdflib.RDF.nodeID)
raw_o = o
o = rdflib.resource.Resource(graph, o)
o_tu = o.value(OBO[REPRESENTS_TU_PREDICATE])
if o_tu:
o_label = o_tu.value(rdflib.RDFS.label)
t = Taxon(label=o_label)
taxon_set.append(t)
parent = Node(taxon=t)
else:
parent = Node()
nd_dict[id(raw_o)] = parent
parentless.add(parent)
child = nd_dict.get(id(s))
if child is None:
raw_s = s
s = rdflib.resource.Resource(graph, s)
s_tu = s.value(OBO[REPRESENTS_TU_PREDICATE])
if s_tu:
s_label = s_tu.value(rdflib.RDFS.label)
t = Taxon(label=s_label)
taxon_set.append(t)
child = Node(taxon=t)
else:
child = Node()
nd_dict[id(raw_s)] = child
else:
if child in parentless:
parentless.remove(child)
parent.add_child(child)
if _DEBUGGING:
out.write("%s %s %s\n" % (str(s), p, o))
out.write("%s\n" % (str(parentless)))
if _DEBUGGING:
out.close()
if len(parentless) != 1:
message = (
"Expecting to find exactly Node (an object of a has_Parent triple) in the graph without a parent. Found %d"
% len(parentless)
)
CUTOFF_FOR_LISTING_PARENTLESS_NODES = 1 + len(
parentless
) # we might want to put in a magic number here to suppress really long output
if len(parentless) > 0 and len(parentless) < CUTOFF_FOR_LISTING_PARENTLESS_NODES:
message += ":\n "
for i in parentless:
if i.label:
message += "\n " + i.label
else:
message += "\n <unlabeled>" + str(id(i))
raise ValueError(message)
else:
sys.exit("no parentless")
return None
tree = Tree(taxon_set=taxon_set)
tree.seed_node = list(parentless)[0]
tree.is_rooted = True
return tree