Art*_*sse 9 python file-io export rdflib python-3.x
我正在尝试使用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'))
Run Code Online (Sandbox Code Playgroud)
此代码导致以下错误:
file.write(g.serialize(format='turtle'))
TypeError : must be str, not bytes
Run Code Online (Sandbox Code Playgroud)
如果我用以下内容替换最后一行:
file.write(str(g.serialize(format='turtle')))
Run Code Online (Sandbox Code Playgroud)
我没有得到错误,但结果是二进制流的字符串表示(单行文本开头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'
Run Code Online (Sandbox Code Playgroud)
问题 如何将图形正确导出到文件中?
Ted*_*ess 13
该串行化方法接受一个目标关键字的文件路径.在您的示例中,您可能希望使用:
g.serialize(destination='output.txt', format='turtle')
Run Code Online (Sandbox Code Playgroud)
代替
file = open("output.txt", "w")
file.write(g.serialize(format='turtle'))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6356 次 |
最近记录: |