Lio*_*pir 5 python printing sparql rdflib dbpedia
我刚刚开始使用 rdflib,我有一个程序需要获取一个人的出生日期(在本例中为 Lewis Carroll)。我的程序就是这样做的,但是当我尝试打印它打印的日期时: (rdflib.term.Literal('1832-01-27', datatype=rdflib.term.URIRef(' http://www.w3.org/ 2001/XMLSchema#date ')),)
我确信有一种简单的方法可以只打印日期,但我还没有找到方法。如果有任何相关性,这是我的代码:
# open a graph
graph = rdflib.Graph()
# load some data
graph.parse('http://dbpedia.org/resource/Lewis_Carroll')
qres = graph.query(
("PREFIX dbpedia: <http://dbpedia.org/resource/>\n"
"PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>\n"
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>\n"
"SELECT ?birth WHERE {\n"
" ?person dbpedia-owl:birthDate ?birth . \n"
" ?person foaf:givenName ?givenName . \n"
" ?person foaf:surname ?surname . \n"
" VALUES ?person { dbpedia:Lewis_Carroll }\n"
" }"
))
print("the graph has %s statements" % len(qres))
for row in qres:
print(row)
Run Code Online (Sandbox Code Playgroud)
小智 6
以下是打印查询中的日期的方法:
>>> for row in qres:
... d = str(row.asdict()['birth'].toPython())
... print(d)
...
1832-01-27
>>>
Run Code Online (Sandbox Code Playgroud)
我解决这个问题的一些线索是http://rdflib.readthedocs.org/en/latest/_modules/rdflib/query.html和 rdflib.term.Literal.toPython() 中记录的 rdflib.query.ResultRow.asDict()记录在http://rdflib.readthedocs.org/en/latest/apidocs/rdflib.html中。
请注意, row.asdict()['birth'].toPython() 是一个 datetime.date 对象。