本文整理汇总了Python中rdflib.graph.Graph.parse方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.parse方法的具体用法?Python Graph.parse怎么用?Python Graph.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rdflib.graph.Graph
的用法示例。
在下文中一共展示了Graph.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_e
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
def test_e():
"""Test reading N3 from a BytesIO over the string object"""
g = Graph()
g.parse(source=BytesIO(rdf_utf8), format='n3')
v = g.value(subject=URIRef("http://www.test.org/#CI"),
predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel"))
assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr')
示例2: test_xml_e
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
def test_xml_e():
"""Test reading XML from a BytesIO created from utf8 encoded string"""
g = Graph()
g.parse(source=BytesIO(rdfxml_utf8), format='xml')
v = g.value(subject=URIRef("http://www.test.org/#CI"),
predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel"))
assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr')
示例3: test_b
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
def test_b():
"""Test reading N3 from a utf8 encoded string as data"""
g = Graph()
g.parse(data=rdf_utf8, format='n3')
v = g.value(subject=URIRef("http://www.test.org/#CI"),
predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel"))
assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr')
示例4: command
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
def command(self):
assert self.opts.infile is not None, "Must specify an input file"
g = Graph()
fp = open(self.opts.infile)
g.parse(fp, format=self.opts.format)
fp.close()
def check_mbox(mbox):
print "Checking:", mbox
for _x in g.triples((None, FOAF["mbox"], URIRef(mbox))):
sys.exit(0)
mbox_sha1sum = sha1(mbox).hexdigest()
print "Checking", mbox_sha1sum
for _x in g.triples((None, FOAF["mbox_sha1sum"], Literal(mbox_sha1sum))):
sys.exit(0)
for line in sys.stdin.readlines():
line = line.strip()
if line.startswith("From:"):
header, val = line.split(":", 1)
val = val.strip()
m = _from_re.match(val)
if m:
mbox = "mailto:" + m.groupdict()["addr"]
check_mbox(mbox)
check_mbox("mailto:" + val)
sys.exit(1)
示例5: test_c
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
def test_c():
"""Test reading N3 from a codecs.StreamReader, outputting unicode"""
g = Graph()
# rdf_reader.seek(0)
g.parse(source=rdf_reader, format='n3')
v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel"))
assert v==Literal(u"C\u00f4te d'Ivoire", lang='fr')
示例6: _testPositive
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
def _testPositive(uri, manifest):
if verbose:
write(u"TESTING: %s" % uri)
result = 0 # 1=failed, 0=passed
inDoc = first(manifest.objects(uri, TEST["inputDocument"]))
outDoc = first(manifest.objects(uri, TEST["outputDocument"]))
expected = Graph()
if outDoc[-3:] == ".nt":
format = "nt"
else:
format = "xml"
expected.parse(cached_file(outDoc), publicID=outDoc, format=format)
store = TestStore(expected)
if inDoc[-3:] == ".nt":
format = "nt"
else:
format = "xml"
try:
store.parse(cached_file(inDoc), publicID=inDoc, format=format)
except ParserError, pe:
write("Failed '")
write(inDoc)
write("' failed with")
raise pe
try:
write(type(pe))
except:
write("sorry could not dump out error.")
result = 1
示例7: handle
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
def handle(self, *args, **options):
if not args:
raise CommandError("No file or resource specified.")
info = options.get('verbosity') >= 2
store_id = options.get('store')
context_id = options.get('context')
source = args[0]
if info:
print "Parsing {0}".format(source)
intermediate = Graph()
try:
intermediate.parse(source, format=options.get('format'))
except Exception as e:
raise CommandError(e)
if info:
print "Parsed {0} triples".format(len(intermediate))
identifier = URIRef(context_id) if context_id else BNode()
graph = utils.get_named_graph(identifier, store_id=store_id)
if info:
print "Storing {0} triples".format(len(intermediate))
for triple in intermediate:
graph.add(triple)
if info:
print "Done"
示例8: _testNegative
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
def _testNegative(uri, manifest):
if verbose:
write(u"TESTING: %s" % uri)
result = 0 # 1=failed, 0=passed
inDoc = first(manifest.objects(uri, TEST["inputDocument"]))
store = Graph()
test = BNode()
results.add((test, RESULT["test"], uri))
results.add((test, RESULT["system"], system))
try:
if inDoc[-3:] == ".nt":
format = "nt"
else:
format = "xml"
store.parse(cached_file(inDoc), publicID=inDoc, format=format)
except ParserError:
results.add((test, RDF.type, RESULT["PassingRun"]))
# pass
else:
write(u"""Failed: '%s'""" % uri)
results.add((test, RDF.type, RESULT["FailingRun"]))
result = 1
return result
示例9: GraphAggregates2
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
class GraphAggregates2(unittest.TestCase):
known_issue = True
sparql = True
def setUp(self):
memStore = plugin.get('IOMemory',Store)()
self.graph1 = Graph(memStore,URIRef("http://example.com/graph1"))
self.graph2 = Graph(memStore,URIRef("http://example.com/graph2"))
self.graph3 = Graph(memStore,URIRef("http://example.com/graph3"))
for n3Str,graph in [(testGraph1N3,self.graph1),
(testGraph2N3,self.graph2),
(testGraph3N3,self.graph3)]:
graph.parse(StringIO(n3Str),format='n3')
self.graph4 = Graph(memStore,RDFS)
self.graph4.parse(RDFS.uri)
self.G = ConjunctiveGraph(memStore)
def testAggregateSPARQL(self):
print sparqlQ
rt = self.G.query(sparqlQ)
assert len(rt) > 1
#print rt.serialize(format='xml')
LOG_NS = Namespace(u'http://www.w3.org/2000/10/swap/log#')
rt=self.G.query(sparqlQ2,initBindings={u'?graph' : URIRef("http://example.com/graph3")})
#print rt.serialize(format='json')
assert rt.serialize('python')[0] == LOG_NS.N3Document,repr(list(rt.serialize('python')))
示例10: get_graph
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
def get_graph(self):
# Read owl (turtle) file
owl_graph = Graph()
if self.file[0:4] == "http":
owl_txt = urllib2.urlopen(self.file).read()
else:
owl_txt = open(self.file, "r").read()
# This is a workaround to avoid issue with "#" in base prefix as
# described in https://github.com/RDFLib/rdflib/issues/379. When
# the fix is introduced in rdflib these 2 lines will be replaced by:
# self.owl.parse(owl_file, format='turtle')
owl_txt = owl_txt.replace("http://www.w3.org/2002/07/owl#", "http://www.w3.org/2002/07/owl")
owl_graph.parse(data=owl_txt, format="turtle")
if self.import_files:
for import_file in self.import_files:
# Read owl (turtle) file
import_graph = Graph()
if self.file[0:4] == "http":
import_txt = urllib2.urlopen(import_file).read()
else:
import_txt = open(import_file, "r").read()
# This is a workaround to avoid issue with "#" in base prefix
# as described in https://github.com/RDFLib/rdflib/issues/379,
# When the fix is introduced in rdflib these 2 lines will be
# replaced by:
# self.owl.parse(owl_file, format='turtle')
import_txt = import_txt.replace("http://www.w3.org/2002/07/owl#", "http://www.w3.org/2002/07/owl")
import_graph.parse(data=import_txt, format="turtle")
owl_graph = owl_graph + import_graph
return owl_graph
示例11: test_xml_a
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
def test_xml_a():
"""Test reading XML from a unicode object as data"""
g = Graph()
g.parse(data=rdfxml, format='xml')
v = g.value(subject=URIRef("http://www.test.org/#CI"),
predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel"))
assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr')
示例12: BaseParser
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
class BaseParser(object):
""" This is an abstract class that different parser formats classes must override. """
def __init__(self, file, format, db_config_path):
""" Sole constructor.
:param file: Path to input file location.
:param format: String defining file format (e.g. 'nt')
:param db_config_path: Path to redis database configuration file (see geodb.GeoDB class).
"""
self.graph = Graph()
self.file = file
self.format = format
self.db = GeoDB(db_config_path)
def parse(self, feed_database=False):
""" Reads and parses the input file.
See RDFLib documentation (http://rdflib.readthedocs.org/en/latest/)
for further information.
"""
log.debug('Parsing input file...')
self.graph.parse(self.file, format=self.format)
log.debug('Number of parsed entries: %d' % len(self.graph))
if feed_database:
self.feed_database()
def feed_database(self):
""" Abstract method. It fills the database depending on the data model and the file format. """
raise NotImplementedError('This is an abstract method!')
def get_db(self):
""" Retrieves the redis database instance. """
return self.db
示例13: testIssue29
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
def testIssue29(self):
input = """@prefix foo-bar: <http://example.org/> .
foo-bar:Ex foo-bar:name "Test" . """
g = Graph()
g.parse(data=input, format="n3")
示例14: align_graphs_from_files
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
def align_graphs_from_files(ontology_path_1, ontology_path_2,
param_path, format=None):
"""align ontology graphs from RDF files in 'ontology_path_1'
and 'ontology_path_2' with the help of parameters
from the file in 'param_path'
"""
# get graphs from files
if not format:
ontology_1 = Graph()
ontology_1.parse(ontology_path_1,
format=guess_format(ontology_path_1))
ontology_2 = Graph()
ontology_2.parse(ontology_path_2,
format=guess_format(ontology_path_2))
else:
ontology_1 = Graph(ontology_path_1, format=format)
ontology_2 = Graph(ontology_path_2, format=format)
# get parameters for alignment from file
parameters = dict()
exec(compile(open(param_path, "rb").read(), param_path, 'exec'),
parameters)
# align graphs with parameters
yield from align_graphs(ontology_1, ontology_2, parameters)
示例15: reduce
# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import parse [as 别名]
def reduce(mode='object'):
# input comes from stdin
previous_key = None
graph = Graph()
# load a triples with same _key into a model
for line in sys.stdin:
line = line.strip()
current_key, triple = line.split('\t', 1)
# all lines having same key have
# been completely processed
if current_key != previous_key and previous_key != None:
if mode == 'object':
#print('gggg', graph.serialize(format='nt'))
replaceObjectUri(graph)
elif mode == 'subject':
replaceSubjectUri(graph)
# clear graph
graph = Graph()
# load triple triple into temp graph
# for easier processing
tmp_graph = Graph()
tmp_graph.parse(data=triple,
format="nt")
# get triple from temporary graph
for sub, pred, obj in tmp_graph:
# add to current graph
graph.add((sub, pred, obj))
previous_key = current_key
if mode == 'object':
#print('gggg', graph)
replaceObjectUri(graph)
elif mode == 'subject':
replaceSubjectUri(graph)