我正在尝试使用 Python v3.6.5 中的 RDFlib v4.2.2 解析海龟格式的数据文件,在 OS X 10.14.3 Mojave 上运行。根据最初的错误消息,我发现海龟文件缺少词汇表 URI 前缀: @prefix xsd: <http://www.w3.org/2001/XMLSchema#>
.
如果我将这一行添加到文件的标题中,它会按预期工作。但最好在不编辑数据文件的情况下完成此操作,因为数据源可以不时更新它。作为 RDF 和 Turtle 的新手,我扫描了 RDFlib documentation并决定绑定(bind)前缀就是我想要的:
from rdflib import Graph
g = Graph()
g.namespace_manager.bind('prefix', 'xsd:http://www.w3.org/2001/XMLSchema#')
g.parse( 'currency.ttl', format='turtle')
但是,没有喜悦。如果有帮助,这里是文件中的标题和一只示例海龟,它描述了不同的货币,取自 Thomson Reuters Open PermID project :
@prefix tr-common: <http://permid.org/ontology/common/> .
@prefix tr-currency: <http://permid.org/ontology/currency/> .
@prefix skos: <http://www.w3.org/2004/02/skos/core#> .
<https://permid.org/1-500191>
a tr-currency:Currency ;
tr-common:hasPermId "500191"^^xsd:string ;
tr-currency:decimalPlaces "0"^^xsd:decimal ;
tr-currency:isCurrencyOf <http://sws.geonames.org/1835841> ;
tr-currency:isISOHistorical false ;
tr-currency:isPrimaryCurrencyOf <http://sws.geonames.org/1835841> ;
tr-currency:iso4217 "KRW"^^xsd:string ;
tr-currency:iso4217Numeric "410"^^xsd:string ;
skos:prefLabel "Korean (South) Won" .
是否可以补充海龟文件中包含的前缀 URI,如果可以,如何补充?
我注意到缺失的词汇 XSD 是 Turtle grammar 的一个组成部分。规范。我想知道在某些实现中明确声明它是否是可选的?
最佳答案
不,您发布的海龟片段无效。 XSD 需要显式声明。
您可以将文件作为字符串读取并添加 xsd 前缀,然后使用 RDFLib 进行解析,如下所示:
with open('currency.ttl') as in_file:
ttl_str = '@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .' + in_file.read()
g.parse(data=ttl_str, format='turtle')
假设您正在解析有效的海龟,则绑定(bind) xsd 前缀的方式存在错误。你想要:
from rdflib import Graph
g = Graph()
g.namespace_manager.bind('xsd', 'http://www.w3.org/2001/XMLSchema#')
g.parse( 'currency.ttl', format='turtle')
我建议看看 RDFLib documentation关于命名空间管理。
XSD 命名空间包含在 RDFLib 中。它导入为:
从 rdflib.namespace 导入 XSD
关于python - 使用python/rdflib解析turtle,无法指定IRI前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55182311/