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

2024-05-16 07:32:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Python3.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'

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


Tags: orghttpdataprefixexamplewwwrdffile
3条回答

我在Python3.7.3中遇到了完全相同的问题。使用“destination”参数,正如前面的回答所建议的那样,对我没有帮助,因为我希望将三元组附加到RDF文件中。我知道问题来自于Python3中byte是替换Python2字符串的数据结构。设置序列化方法的“encoding”参数也不起作用。我在这个post中找到了一个工作解决方案:对结果字符串进行解码。相反

g.serialize(format='turtle')

使用

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

或者你正在使用的任何格式。希望能有所帮助。

serialize method接受作为文件路径的destination关键字。在您的示例中,您需要使用:

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

而不是

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

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

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

相关问题 更多 >