如何使用RDFLib将图表导出为RDF文件

16
我正在尝试使用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个回答

21

serialize方法 接受一个目标关键字作为文件路径。在您的示例中,您需要使用:

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

与其

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

@lawlesst:我遇到了同样的问题,但如果我不想更改目录,串行器就可以正常工作,但是一旦我将其更改为另一个驱动器,它会返回 IOError: [Errno 2] No such file or directory: Skane/Output/Skane/ontolog_output/NVDB_RA1/NVDB_RNO_V5042_RDF.owl。如您所见,目录名称丢失了,这是因为使用了 urlparse() 函数。我是漏掉了什么还是代码中有 bug? - msc87
@msc87 我没有遇到过这个问题。RDFLib 可以将文件序列化到其他路径。我经常使用它。你是否提供了绝对文件路径?我建议尝试一下。同时,尝试使用类似于“/tmp/myfile.owl”的路径,看看是否会出现类似的错误。 - Ted Lawless
@lawlesst:D:/Skane/Output/Skane/ontolog_output/NVDB_RA1/NVDB_RNO_V5042_RDF.owl 是我定义的路径。它在 /tmp 中没有返回任何错误,并且文件已创建。使用 Skane/Output/Skane/ontolog_output/NVDB_RA1/NVDB_RNO_V5042_RDF.owl 也可以,在 c 目录中创建该文件,但如果我将其更改为 D,它会返回错误,如果我使用 "d",则不会返回错误,也不会创建该文件。 - msc87
@msc87 这似乎是一个Windows文件路径问题。需要对反斜杠进行转义。请参考《Dive into Python》中的这篇入门文章 - Ted Lawless

2
我在使用Python 3.7.3时遇到了完全相同的问题。如前面的回答建议的使用“destination”参数并不能帮助我,因为我想将三元组附加到RDF文件中。我理解问题出在Python3中,字节是替换Python2字符串的数据结构。将序列化方法的“encoding”参数设置为UTF-8也没有起作用。我在这个帖子中找到了一个有效的解决方案:对生成的字符串进行解码。
g.serialize(format='turtle')

"最初的回答":使用
g.serialize(format='turtle').decode('utf-8')

最初的回答。无论您使用哪种格式。希望这能帮到你。

非常感谢,这正是我们在重构代码以处理Unicode时遇到的问题。 - Paco

2

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

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

-1

欢迎来到 Stack Overflow。当您发布答案时,请解释您发布的代码,并提供一些细节。请参阅:https://stackoverflow.com/help/how-to-answer - Fukiyel
请在答案中对您的代码进行一些解释。 - Partho63

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接