[尝试对本地ttl文件运行SPARQL查询。我之前已经成功完成了此操作,但没有成功。我怀疑这与名称空间有关。
尝试打印出查询是什么,而我得到的只是“ rdflib.plugins.sparql.processor.SPARQLResult at 0x1fbe05d3400”,所以那里有东西。
这里是ttl文件
# filename: ex050.ttl
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
<http://www.learningsparql.com/ns/demo#i93234>
foaf:nick "Dick" ;
foaf:givenname "Richard" ;
foaf:mbox "[email protected]" ;
foaf:surname "Mutt" ;
foaf:workplaceHomepage <http://www.philamuseum.org/> ;
foaf:aimChatID "bridesbachelor" .
这是触发SPARQL查询的python代码
filename = "C:/DataStuff/SemanticOntology/LearningSPARQLExamples/ex050.ttl"
import rdflib
g = rdflib.Graph()
result = g.parse(filename, format='ttl')
query = """
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?propertyLabel ?value
WHERE
{
?s ?property ?value .
?property rdfs:label ?propertyLabel .
}
"""
results=g.query(query)
print('Results!')
for row in results:
print(row)
我知道这是我搞砸的基本知识。请帮助!
[好-放宽RDFILB规范(https://buildmedia.readthedocs.org/media/pdf/rdflib/4.2.1/rdflib.pdf),我发现您可以一个接一个地解析多个文件/ URL。结果是一个合并的文件。因此,知道我感兴趣的foaf文件可以在以下位置下载http://www.xmlns.com/foaf/spec/index.rdf
我得到了文件,然后将程序更改为:
filename = "C:/DataStuff/SemanticOntology/LearningSPARQLExamples/ex050.ttl"
filename2 = "C:/DataStuff/SemanticOntology/LearningSPARQLExamples/index.rdf"
g = rdflib.Graph()
g.parse(filename, format='ttl')
g.parse(filename2)
query = """
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?propertyLabel ?value
WHERE
{
?s ?property ?value .
?property rdfs:label ?propertyLabel .
}
"""
results=g.query(query)
print('Results!')
for row in results:
print(row)
然后工作,打印出来:
Results!
(rdflib.term.Literal('Given name'), rdflib.term.Literal('Richard'))
(rdflib.term.Literal('Surname'), rdflib.term.Literal('Mutt'))
(rdflib.term.Literal('AIM chat ID'), rdflib.term.Literal('bridesbachelor'))
(rdflib.term.Literal('personal mailbox'), rdflib.term.Literal('[email protected]'))
(rdflib.term.Literal('workplace homepage'), rdflib.term.URIRef('http://www.philamuseum.org/'))
(rdflib.term.Literal('nickname'), rdflib.term.Literal('Dick'))
即使我没有定义那些属性,也要打印出原始数据文件中所有人类可读属性的标签。
我想可以直接使用第二个parse语句中的URL来跳过下载文件的步骤。但是,我无法像在公司环境中那样执行此操作,也看不到将解析语句与代理一起使用的方法。