如何使用RDFLib导出RDF文件中的图形

时间:2014-05-07 14:14:52

标签: python python-3.x file-io export rdflib

我试图在Python 3.4中使用RDFLib生成RDF数据。

一个最小的例子:

from rdflib import Namespace, URIRef, Graph
from rdflib.namespace import RDF, FOAF

data = Namespace("http://www.example.org#")

g = Graph()

g.add( (URIRef(data.Alice), RDF.type , FOAF.person) )
g.add( (URIRef(data.Bob), RDF.type , FOAF.person) )
g.add( (URIRef(data.Alice), FOAF.knows, URIRef(data.Bob)) )

#write attempt
file = open("output.txt", mode="w")
file.write(g.serialize(format='turtle'))

此代码导致以下错误:

file.write(g.serialize(format='turtle'))
TypeError : must be str, not bytes

如果我用以下内容替换最后一行:

file.write(str(g.serialize(format='turtle')))

我没有收到错误,但结果是二进制流的字符串表示形式(以b'开头的单行文本):

b'@prefix ns1: <http://xmlns.com/foaf/0.1/> .\n@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n@prefix xml: <http://www.w3.org/XML/1998/namespace> .\n@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n\n<http://www.example.org#Alice> a ns1:person ;\n    ns1:knows <http://www.example.org#Bob> .\n\n<http://www.example.org#Bob> a ns1:person .\n\n'

问题 如何将图形正确导出到文件中?

4 个答案:

答案 0 :(得分:9)

serialize method接受作为文件路径的目标关键字。在您的示例中,您可能希望使用:

g.serialize(destination='output.txt', format='turtle'))

而不是

file = open("output.txt", "w")
file.write(g.serialize(format='turtle'))

答案 1 :(得分:1)

我在Python3.7.3中工作时遇到了完全相同的问题。如上一个答案中所述,使用“目标”参数并没有帮助我,因为我希望将三元组附加到rdf文件中。我知道问题出在以下事实:在Python3中,字节是替换了Python2字符串的数据结构。设置序列化方法的'encoding'参数也不起作用。我在此post中找到了一个可行的解决方案:对生成的字符串进行编码。代替

g.serialize(format='turtle')

使用

g.serialize(format='turtle').encode('utf-8')

或您使用的任何格式。希望有帮助。

答案 2 :(得分:0)

在函数中写文件名对我有用:

g.serialize('output_file.ttl',format='ttl')

答案 3 :(得分:-1)

g.serialize(目标=“ file:G:/RootFolder/Tests_rdflib/Test_rdflib_1/output2.xml”,format ='xml')