Python 使用csv文件作为输入创建RDF文件
我需要用rdflib将csv文件转换为rdf,我已经有了读取csv的代码,但我不知道如何将其转换为rdf 我有以下代码:Python 使用csv文件作为输入创建RDF文件,python,rdflib,Python,Rdflib,我需要用rdflib将csv文件转换为rdf,我已经有了读取csv的代码,但我不知道如何将其转换为rdf 我有以下代码: import csv from rdflib.graph import Graph # Open the input file with open('data.csv', 'rb') as fcsv: g = Graph() csvreader = csv.reader(fcsv) y = True for row in csvreader:
import csv
from rdflib.graph import Graph
# Open the input file
with open('data.csv', 'rb') as fcsv:
g = Graph()
csvreader = csv.reader(fcsv)
y = True
for row in csvreader:
if y:
names = row
y = False
else:
for i in range(len(row)):
continue
print(g.serialize(format='xml'))
fcsv.close()
有人能解释一下并给我举个例子吗?中有一个“用于将CSV半自动转换为RDF的命令行工具”
csv2rdf.py\
-b\
-p\
[-D]\
[-c]\
[-i]\
[-l]\
[-s][-o]\
[-f配置文件]\
[--col]\
[--道具]\
示例csv文件
感谢KRontheWeb,我使用以下示例csv文件来回答您的问题:
导入库
读取csv文件
定义图形“g”和名称空间
创建三元组并将其添加到图形“g”
它有点密集,但每个g.add()都由三部分组成:主语、谓语、宾语。有关更多信息,请查看真正友好的rdflib文档,第1.1.3节及以后的内容,网址为
请注意:
- 我从rdflib借用名称空间,自己创建了一些名称空间李>
- 只要有可能,最好定义数据类型李>
- 我从地址创建URI(字符串处理示例)
检查结果
输出的一个片段:
<http://example.org/people/Jake> a ns2:Person ;
ns1:address "12E Street 98"^^xsd:string ;
ns1:name "Jake"^^xsd:string ;
ns2:age 42 .
看看最近添加到RDFlib工具系列中的工具。它专门用于解析CSV并将其序列化为RDF。欢迎使用SO!你应该包括你已经拥有的东西,以便其他人在上面构建,并帮助你知道ref格式吗?我将使用xml格式
"Name";"Address";"Place";"Country";"Age";"Hobby";"Favourite Colour"
"John";"Dam 52";"Amsterdam";"The Netherlands";"32";"Fishing";"Blue"
"Jenny";"Leidseplein 2";"Amsterdam";"The Netherlands";"12";"Dancing";"Mauve"
"Jill";"52W Street 5";"Amsterdam";"United States of America";"28";"Carpentry";"Cyan"
"Jake";"12E Street 98";"Amsterdam";"United States of America";"42";"Ballet";"Purple"
import pandas as pd #for handling csv and csv contents
from rdflib import Graph, Literal, RDF, URIRef, Namespace #basic RDF handling
from rdflib.namespace import FOAF , XSD #most common namespaces
import urllib.parse #for parsing strings to URI's
url='https://raw.githubusercontent.com/KRontheWeb/csv2rdf-tutorial/master/example.csv'
df=pd.read_csv(url,sep=";",quotechar='"')
# df # uncomment to check for contents
g = Graph()
ppl = Namespace('http://example.org/people/')
loc = Namespace('http://mylocations.org/addresses/')
schema = Namespace('http://schema.org/')
for index, row in df.iterrows():
g.add((URIRef(ppl+row['Name']), RDF.type, FOAF.Person))
g.add((URIRef(ppl+row['Name']), URIRef(schema+'name'), Literal(row['Name'], datatype=XSD.string) ))
g.add((URIRef(ppl+row['Name']), FOAF.age, Literal(row['Age'], datatype=XSD.integer) ))
g.add((URIRef(ppl+row['Name']), URIRef(schema+'address'), Literal(row['Address'], datatype=XSD.string) ))
g.add((URIRef(loc+urllib.parse.quote(row['Address'])), URIRef(schema+'name'), Literal(row['Address'], datatype=XSD.string) ))
print(g.serialize(format='turtle').decode('UTF-8'))
<http://example.org/people/Jake> a ns2:Person ;
ns1:address "12E Street 98"^^xsd:string ;
ns1:name "Jake"^^xsd:string ;
ns2:age 42 .
g.serialize('mycsv2rdf.ttl',format='turtle')