首页 > 解决方案 > 使用 csv 文件创建 RDF 文件包含日期值作为输入

问题描述

我有一个如图所示的数据,想把它转换成RDF文件。我使用了以下代码 我的 CSV 数据

#import libraries 
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
#Read file
df=pd.read_csv("filename.csv",sep="\t",quotechar='"')
#creating graph
g = Graph()
continent = Namespace('http://example.org/continent/')
loc= Namespace('http://mylocations.org/addresses/')
schema = Namespace('http://schema.org/')

for index, row in df.iterrows():
    g.add((URIRef(continent+row[0]), RDF.type, URIRef(continent+'Iso_code')))
    g.add((URIRef(continent+row[1]), RDF.type, URIRef(continent+'Continent')))
    g.add((URIRef(continent+row[2]), RDF.type, URIRef(continent+'Location')))
    g.add((URIRef(continent+row[2]), URIRef(continent+'is_in'), URIRef(continent+row[1])))
    g.add((URIRef(continent+row[2]), URIRef(continent+'total_cases'), Literal(row[4], datatype=XSD.integer)))
    g.add((URIRef(continent+row[2]), URIRef(continent+'date'), Literal(row[3],datatype=XSD.date)))
# save graph
g.serialize('mycsv2rdf.ttl',format='turtle')

我是否正确创建了 rdf ?创建的文件具有类似的数据。

@prefix ns1: <http://example.org/continent/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
ns1:AFG a ns1:Iso_code .
ns1:Afghanistan a ns1:Location ;
ns1:date "0101-01-01"^^xsd:date,
    "0201-01-01"^^xsd:date,
    "0301-01-01"^^xsd:date,
    "0401-01-01"^^xsd:date,
    "0501-01-01"^^xsd:date,
    "0601-01-01"^^xsd:date,
    "2401-01-01"^^xsd:date,
    "2501-01-01"^^xsd:date,
    "2601-01-01"^^xsd:date,
    "2701-01-01"^^xsd:date,
    "2801-01-01"^^xsd:date,
    "2901-01-01"^^xsd:date ;
ns1:is_in ns1:Asia ;
ns1:total_cases 1,
    2,
    4 .
ns1:Asia a ns1:Continent .

不按日期插入值。帮我做什么。如何将日期明智的值插入图表。

标签: pythonrdflibturtle-rdf

解决方案


不,您的数据不正确,有几个方面:

  • 您的日期需要正确解析。考虑使用 Python datatime.strtotime(),然后将日期对象提供给 RDFlib 的Literal
  • 您已经声明了一个类Iso_code并创建了它的实例,例如ns1:AFG,但您没有将任何东西链接到它。

实际上,您的 RDF 没有任何意义:您可能需要有一个主题ns1:Afghanistan(但请注意,您的 URIns1包含/continent/但阿富汗不是大陆),然后将 thigs 链接到它。您已经声明了一系列不相关的主题,例如ns1:AFG, ns1:Afghanistan, ns1:date

你可能想要这样的东西:

@prefix ns1: <http://example.org/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix time: <http://www.w3.org/2006/time#> .

ns1:AFG a ns1:Iso_code .

ns1:Asia a ns1:Continent .

ns1:Afghanistan 
    a ns1:Location ;
    ns1:hasIsoCode ns1:AFG ;
    ns1:hasDatedCases [
       time:hasTime "2020-02-24"^^xsd:date ;
       ns1:totalCases 1 ;
       ns1:newCases 1 ;
    ] ,
    [
       time:hasTime "2020-02-25"^^xsd:date ;
       ns1:totalCases 1 ;
       ns1:newCases 0 ;
    ] ,
    ...
    ns1:is_in ns1:Asia ;
.


推荐阅读