当前位置: 首页>>代码示例>>Python>>正文


Python ConjunctiveGraph.namespaces方法代码示例

本文整理汇总了Python中rdflib.ConjunctiveGraph.namespaces方法的典型用法代码示例。如果您正苦于以下问题:Python ConjunctiveGraph.namespaces方法的具体用法?Python ConjunctiveGraph.namespaces怎么用?Python ConjunctiveGraph.namespaces使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rdflib.ConjunctiveGraph的用法示例。


在下文中一共展示了ConjunctiveGraph.namespaces方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: from_string

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import namespaces [as 别名]
 def from_string(self, uri, text, format="xml", encoding="utf-8"):
     self.reset()
     self.set_uri(uri)
     t = TextInputSource(text, system_id=uri)
     t.setEncoding(encoding)
     g = ConjunctiveGraph(identifier=self.uri)
     g = g.parse(t, format)
     for prefix, ns in g.namespaces():
         self.add_namespace(prefix, ns)
     for s,p,o in g.triples((self.uri, None, None)):
         self.add_triple(p, o)
开发者ID:benosteen,项目名称:RDFobject,代码行数:13,代码来源:rdfobject.py

示例2: from_url

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import namespaces [as 别名]
 def from_url(self, url, uri=None, format="xml",  encoding="utf-8"):
     self.reset()
     if not uri:
         self.set_uri(url)
     else:
         self.set_uri(uri)
     g = ConjunctiveGraph(identifier=self.uri)
     g = g.parse(url, format)
     for prefix, ns in g.namespaces():
         self.add_namespace(prefix, ns)
     for s,p,o in g.triples((self.uri, None, None)):
         self.add_triple(p, o)
开发者ID:benosteen,项目名称:RDFobject,代码行数:14,代码来源:rdfobject.py

示例3: from_string

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import namespaces [as 别名]
    def from_string(self, rdf_manifest_string, format="xml"):
        t = TextInputSource(rdf_manifest_string)
        g = ConjunctiveGraph()
        g = g.parse(t, format)
        
        for s,p,o in g.triples((None, None, None)):
            if s not in self.items:
                self.items.append(s)
            if p == NAMESPACES['rdf']['type']:
                self.items_rdfobjects.setdefault(s,RDFobject(uri=s)).add_type(o)
            else:
                self.items_rdfobjects.setdefault(s,RDFobject(uri=s)).add_triple(p, o)

        for prefix, ns in g.namespaces():
            self.add_namespace(prefix ,ns)
开发者ID:benosteen,项目名称:RDFobject,代码行数:17,代码来源:manifest.py

示例4: convert

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import namespaces [as 别名]
def convert(teifile, namespace):
	#graph_uri = "http://contextus.net/resource/blue_velvet/"
	
	ns = Namespace(namespace)

	graph = ConjunctiveGraph()
	graph.load(teifile, format="rdfa")
	
	graph.bind("default", ns)
	
	to_update = ""

	for prefix, nsuri in graph.namespaces(): 
		#print("prefix: " + str(prefix) + " - " + str(nsuri))
		if nsuri in ns:
			to_update = nsuri
			
	for s, p, o in graph:
#    		print s, p, o
    		if to_update != "" and to_update in s:
    			graph.remove((s, p, o))
			s = URIRef(s.replace(to_update, ns))			
			graph.add((s, p, o))
	
	act = ""
	scene = ""
	line = ""
	char = 0
	loc = 0
	
	
	#timeline = ns['timeline/narrative']
	#graph.add((timeline, RDF.type, ome['Timeline']))

	tree = ET.parse(teifile)
	cast = dict()
	
	titleNode = tree.find('//title')
	
	castItems = tree.findall('/text/body/div1/castList//castItem')
	for castItem in castItems:
		actorNode = castItem.find('actor')
		roleNode = castItem.find('role')

		if roleNode != None:
			id = roleNode.get("{http://www.w3.org/XML/1998/namespace}id")
		
		#print("Found castItem!")

		actor = None
		role = None

		# Check to see if we already have an entry
		if(roleNode != None and roleNode.get("about")):		

			charname = roleNode.get("about")
			
			if(charname.find(":") > -1):
				nmsp,nom = charname.split(":", 1)		
				charcode =  "character/" + str(char)
				charref = nmsp + ":" + charcode + "]"
				role = extractCURIEorURI(graph, charref,nom[0:-1])
				char += 1		
				#print("1:" + charname + ": adding id " + id + " to " + role)
			else:
				role = extractCURIEorURI(graph, charname)
				#print("2:" + charname + ": adding id " + id + " to " + role)

			cast[id] = role
			graph.add((role, RDF.type, omb['Character']))
			#print(charname + ": adding id " + id + " to " + role)
		
		if(actorNode != None and actorNode.get("about")):
			actor = extractCURIEorURI(graph, actorNode.get("about"))
			graph.add((actor, RDF.type, omb['Being']))

		if actor != None and role != None:
			graph.add((actor, omb['portrays'], role))
			graph.add((role, omb['portrayed-by'], actor))

	eventCount = 1
	groupCount = 1
	prior_event = None
	
	actItems = tree.findall('/text/body/div1')
	ref = ""
	
	for actItem in actItems:
	
		if actItem.get("type") == "act":
			act = actItem.get("n")
		
		sceneItems = actItem.findall('div2')
		
		for sceneItem in sceneItems:
			
			#print("Found sceneItems!")
			
			if sceneItem.get("type") == "scene":
				scene = sceneItem.get("n")		
#.........这里部分代码省略.........
开发者ID:klaffenboeck,项目名称:contextus,代码行数:103,代码来源:tei2onto2.py

示例5: SQLATestCase

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import namespaces [as 别名]
class SQLATestCase(unittest.TestCase):
    identifier = URIRef("rdflib_test")
    dburi = Literal('sqlite://')

    def setUp(self):
        self.store = plugin.get(
            "SQLAlchemy", Store)(identifier=self.identifier)
        self.graph = ConjunctiveGraph(self.store, identifier=self.identifier)
        self.graph.open(self.dburi, create=True)

    def tearDown(self):
        self.graph.destroy(self.dburi)
        try:
            self.graph.close()
        except:
            pass

    def test_registerplugins(self):
        # I doubt this is quite right for a fresh pip installation,
        # this test is mainly here to fill a coverage gap.
        from rdflib_sqlalchemy import registerplugins
        from rdflib import plugin
        from rdflib.store import Store
        registerplugins()
        self.assert_(plugin.get('SQLAlchemy', Store) is not None)
        p = plugin._plugins
        self.assert_(('SQLAlchemy', Store) in p, p)
        del p[('SQLAlchemy', Store)]
        plugin._plugins = p
        registerplugins()
        self.assert_(('SQLAlchemy', Store) in p, p)

    def test_skolemisation(self):
        from rdflib_sqlalchemy.SQLAlchemy import skolemise
        testbnode = BNode()
        statemnt = (michel, likes, testbnode)
        res = skolemise(statemnt)
        self.assert_('bnode:N' in str(res[2]), res)

    def test_deskolemisation(self):
        from rdflib_sqlalchemy.SQLAlchemy import deskolemise
        testbnode = BNode()
        statemnt = (michel, likes, testbnode)
        res = deskolemise(statemnt)
        self.assert_(str(res[2]).startswith('N'), res)

    def test_redeskolemisation(self):
        from rdflib_sqlalchemy.SQLAlchemy import skolemise, deskolemise
        testbnode = BNode()
        statemnt = skolemise((michel, likes, testbnode))
        res = deskolemise(statemnt)
        self.assert_(str(res[2]).startswith('N'), res)

    def test__parse_rfc1738_args(self):
        from rdflib_sqlalchemy.SQLAlchemy import _parse_rfc1738_args
        self.assertRaises(ValueError, _parse_rfc1738_args, 'Not parseable')

    def test_namespaces(self):
        self.assert_(list(self.graph.namespaces()) != [])

    def test_contexts_without_triple(self):
        self.assert_(list(self.graph.contexts()) == [])

    def test_contexts_with_triple(self):
        statemnt = (michel, likes, pizza)
        self.assert_(self.graph.contexts(triple=statemnt) != [])

    def test__len(self):
        self.assert_(self.store.__len__() == 0)

    def test__remove_context(self):
        self.store._remove_context(self.identifier)
开发者ID:IRI-Research,项目名称:rdflib-sqlalchemy,代码行数:74,代码来源:test_sqlalchemy.py

示例6: init

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import namespaces [as 别名]
    # technically, we already created a namespace
    # with the object init (and it added some namespaces as well)
    # By default, your main namespace is the URI of your
    # current working directory, so lets make that simpler:

    myNS = Namespace('http://www.w3.org/2000/10/swap/Primer#')
    primer.bind('', myNS)
    primer.bind('owl', OWL)
    primer.bind('dc', DC)
    primer.bind('swap', 'http://www.w3.org/2000/10/swap/')

    # Lets load it up!

    primer.parse(data=mySource, format='n3')

    # Now you can query, either directly straight into a list:

    [(x, y, z) for x, y, z in primer]

    # or spit it back out (mostly) the way we created it:

    print(primer.serialize(format='n3'))

    # for more insight into things already done, lets see the namespaces

    list(primer.namespaces())

    # lets ask something about the data

    list(primer.objects(myNS.pat, myNS.child))
开发者ID:RDFLib,项目名称:rdflib,代码行数:32,代码来源:swap_primer.py

示例7:

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import namespaces [as 别名]
    u"tmo"   : TMO,
    u"dc"    : DC,
    u"dct"   : DCTERMS,
    u"foaf"  : FOAF,
    u"sioc"  : SIOC,
    u"sioct" : SIOCT,
    u"geo"   : GEO,
    u"mvcb"  : MVCB,
    u"ical"  : ICAL,
    u"xsd"   : XSD,
    u"owl"   : OWL,
    u"skos"  : SKOS,
    u"doap"  : DOAP,
}

for shortname, namespace in namespace_manager.namespaces():
    NSBINDINGS[shortname] = namespace

"""
keyword['LIBEXTRACTOR KEYWORD-TYPE'] = (
    'DC-ELEMENT',
    'DC-TERM',
    'NEPOMUK-ONTOLOGY',         # left part predicate
    'NEPOMUK-CLASS/PROPERTY'    # right part predicate
)
"""

EXTRACTOR_KEYWORD = {}
EXTRACTOR_KEYWORD['album'] = ('title', 'collection', 'nid3', 'albumTitle')
EXTRACTOR_KEYWORD['artist'] = ('creator', '', 'nao', 'creator')
EXTRACTOR_KEYWORD['book title'] = ('title', '', 'nie', 'title')
开发者ID:t00m,项目名称:Vazaar,代码行数:33,代码来源:namespaces.py

示例8: read_manifest

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import namespaces [as 别名]
def read_manifest(item, manifest_file):
    triples = []
    namespaces = {}
    seeAlsoFiles = []
    oxdsClasses = ['http://vocab.ox.ac.uk/dataset/schema#Grouping', 'http://vocab.ox.ac.uk/dataset/schema#DataSet']

    aggregates = item.list_rdf_objects(item.uri, "ore:aggregates")
    
    g = ConjunctiveGraph()
    gparsed = g.parse(manifest_file, format='xml')
    namespaces = dict(g.namespaces())
    #Get the subjects
    subjects = {}
    for s in gparsed.subjects():
        if s in subjects:
            continue
        if type(s).__name__ == 'URIRef':
            if str(s).startswith('file://'):
                ss = str(s).replace('file://', '')
                if manifest_file in ss:
                    subjects[s] = URIRef(item.uri)
                else:
                    manifest_file_path, manifest_file_name = os.path.split(manifest_file)
                    ss = ss.replace(manifest_file_path, '').strip('/')
                    for file_uri in aggregates:
                        if ss in str(file_uri):
                            subjects[s] = URIRef(file_uri)
                            break
                    if not s in subjects:
                        subjects[s] = URIRef(item.uri)
            else:
                subjects[s] = URIRef(s)
        elif type(s).__name__ == 'BNode':
            replace_subject = True
            for o in gparsed.objects():
                if o == s:
                    replace_subject = False
            if replace_subject:
                subjects[s] = URIRef(item.uri)
            else:
                subjects[s] = s
    #Get the dataset type 
    #set the subject uri to item uri if it is of type as defined in oxdsClasses
    datasetType = False
    for s,p,o in gparsed.triples((None, RDF.type, None)):
        if str(o) in oxdsClasses:
            if type(s).__name__ == 'URIRef' and len(s) > 0 and str(s) != str(item.uri) and str(subjects[s]) != str(item.uri):
                namespaces['owl'] = URIRef("http://www.w3.org/2002/07/owl#")
                triples.append((item.uri, 'owl:sameAs', s))
                triples.append((item.uri, RDF.type, o))              
            elif type(s).__name__ == 'BNode' or len(s) == 0 or str(s) == str(item.uri) or str(subjects[s]) == str(item.uri):
                gparsed.remove((s, p, o))
            subjects[s] = item.uri

    #Get the uri for the see also files
    for s,p,o in gparsed.triples((None, URIRef('http://www.w3.org/2000/01/rdf-schema#seeAlso'), None)):
        if type(o).__name__ == 'URIRef' and len(o) > 0:
            obj = str(o)
            if obj.startswith('file://'):
                obj_path, obj_name = os.path.split(obj)
                obj = obj.replace(obj_path, '').strip('/')
            for file_uri in aggregates:
                if obj in str(file_uri):
                    seeAlsoFiles.append(file_uri)
        gparsed.remove((s, p, o))

    #Add remaining triples
    for s,p,o in gparsed.triples((None, None, None)):
        triples.append((subjects[s], p, o))
    return namespaces, triples, seeAlsoFiles
开发者ID:bhavanaananda,项目名称:Pylons-DataFinder,代码行数:72,代码来源:utils.py

示例9: get_vocab_base

# 需要导入模块: from rdflib import ConjunctiveGraph [as 别名]
# 或者: from rdflib.ConjunctiveGraph import namespaces [as 别名]
def get_vocab_base(vocabfile):
    graph = Graph()
    try:
        graph.parse(vocabfile)
    except:
        graph = None
        graph = Graph()
        try:
            graph.parse(vocabfile, format="n3")
        except:
            return (None, None, None)
    identifier = None
    for v in graph.objects(None, namespaces['dc']['identifier']):
        identifier = v
    if not identifier:
        for v in graph.objects(None, namespaces['dcterms']['identifier']):
            identifier = v

    base = None
    if not base:
        for s in graph.subjects(namespaces['rdf']['type'], namespaces['owl']['Ontology']):
            base = s
            break
    if not base:
        for s in graph.subjects(namespaces['dc']['title'], None):
            base = s
            break
    if not base:
        for s in graph.subjects(namespaces['dcterms']['title'], None):
            base = s
            break
    if not base:
        for s in graph.subjects(namespaces['dc']['creator'], None):
            base = s
            break
    if not base:
        for s in graph.subjects(namespaces['dcterms']['creator'], None):
            base = s
            break
    if not base:
        for v in graph.objects(None, namespaces['vann']['preferredNamespaceUri']):
            base = v
            break
    if not base:
        for v in graph.namespaces():
            if v[0] == '':
                base = v[1]
                break

    prefix = None
    vocab_prefixes = graph.objects(None, namespaces['vann']['preferredNamespacePrefix'])
    for vp in vocab_prefixes:
        prefix = vp
    if not prefix and base:
        for v in graph.namespaces():
            if str(v[1]) == str(base):
                prefix = v[0]
                break
    if not prefix and base:
        prefix = base.strip().strip('/').split('/')[-1].strip('#').strip(' ')
    if base:
        base = base.strip()
        if (base[-1]!="/" and base[-1]!="#"):
            base += "#"
    return (identifier, base, prefix)
开发者ID:anusharanganathan,项目名称:Vocab-ox,代码行数:67,代码来源:rdf_helper.py


注:本文中的rdflib.ConjunctiveGraph.namespaces方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。