我正在使用 rdflib。我正在解析包含命名空间前缀的 Turtle 文件。当我从 SPARQL 查询中取回三元组时,它们包含rdflib.term.URIRef
元素,打印如下:
http://resources.data.gov/resources/dcat-us/#public
我的 rdflib 图知道这 usg:
是http://resources.data.gov/resources/dcat-us/#
. 我想转换http://resources.data.gov/resources/dcat-us/#public
回usg:public
打印。
MWE
这是一个文件mwe_schema.ttl
:
@prefix usg: <http://resources.data.gov/resources/dcat-us/#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix dcat: <http://www.w3.org/ns/dcat#> .
@prefix dct: <http://purl.org/dc/terms/#> .
usg:public
a rdfs:Property ;
rdfs:label "public"@en ;
rdfs:comment "Data asset is or could be made publicly available to all without restrictions." ;
.
这是一个程序mwe_demo.py
:
#!/usr/bin/env demonstrate python namespaces
import rdflib
from rdflib import Dataset, Graph, URIRef, Literal, Namespace, BNode
if __name__=="__main__":
g = Graph()
g.parse("mwe_schema.ttl")
for r in g.query(
"""
SELECT DISTINCT ?aSubject ?aPredicate ?anObject
WHERE {
?aSubject ?aPredicate ?anObject
}
"""):
d = r.asdict()
print(d['aSubject'],d['aPredicate'],d['anObject'])
这是实际的输出:
http://resources.data.gov/resources/dcat-us/#public http://www.w3.org/2000/01/rdf-schema#comment Data asset is or could be made publicly available to all without restrictions.
http://resources.data.gov/resources/dcat-us/#public http://www.w3.org/1999/02/22-rdf-syntax-ns#type http://www.w3.org/2000/01/rdf-schema#Property
http://resources.data.gov/resources/dcat-us/#public http://www.w3.org/2000/01/rdf-schema#label public
这是我想要的输出:
usg:public rdfs:comment rdfs:Property
usg:public http://www.w3.org/1999/02/22-rdf-syntax-ns#type rdfs:Property
usg:public rdfs:label public
(我将单独处理将最后一个public
变成`“public”@en)。