2011-01-10 144 views
4

我想使用一個簡短的前綴來指定rdflib中的命名空間,但我遇到了麻煩。我想答案一定很簡單。這是有問題的代碼:在RDFLIB中使用前綴

g = rdflib.parse("some_rdf.rdf") 

rdf=rdflib.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") 

print "Name Spaces:" 

for ns in g.namespaces(): 
    print ns 

print "Matching Triples" 
print "length of type full uri",len([i for i in g.triples((None,rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),None))]) 
print "length of type truncated uri",len([i for i in g.triples((None,rdflib.term.URIRef('rdf:type'),None))]) 
print "length of type , using namespace",len([i for i in g.triples((None,rdf.type,None))]) 

,輸出是:

Name Spaces: 

('xml', rdflib.term.URIRef('http://www.w3.org/XML/1998/namespace')) 
(u'foaf', rdflib.term.URIRef('http://xmlns.com/foaf/0.1/')) 
(u'z', rdflib.term.URIRef('http://www.zotero.org/namespaces/export#')) 
('rdfs', rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#')) 
(u'bib', rdflib.term.URIRef('http://purl.org/net/biblio#')) 
(u'dc', rdflib.term.URIRef('http://purl.org/dc/elements/1.1/')) 
(u'prism', rdflib.term.URIRef('http://prismstandard.org/namespaces/1.2/basic/')) 
('rdf', rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#')) 
(u'dcterms', rdflib.term.URIRef('http://purl.org/dc/terms/')) 
Matching Triples 
length of type full uri 132 
length of type truncated uri 0 !!!This is wrong should be 132 
length of type , using namespace 132 

我在做什麼錯?

回答

4

你試圖在第二種情況下使用它們的方式不受RDFLib的支持。 你可以不喜歡......

rdf=rdflib.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")

rdflib.term.URIRef(rdf+'type')

rdflib.term.URIRef(rdf['type'])

我很喜歡他們的方式它在你的第三個案例表達爲什麼,不堅持那個?

順便說一句 - 在RDF命名空間中RDFLib已經創建,你可以做...

from rdflib.namespace import RDF 
#RDF <-- rdf.namespace.ClosedNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#') 
+0

謝謝你,這個工程。我同意第三種方式很好,我將從現在開始使用它。 – tjb 2011-01-11 08:54:41