python - 使用 csv 文件创建 RDF 文件包含日期值作为输入
问题描述
我有一个如图所示的数据,想把它转换成RDF文件。我使用了以下代码
#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 .
不按日期插入值。帮我做什么。如何将日期明智的值插入图表。
解决方案
不,您的数据不正确,有几个方面:
- 您的日期需要正确解析。考虑使用 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 ;
.
推荐阅读
- python - 在 Flask 中,有没有办法在每个视图之前运行一些代码?
- sql-server - 使用 FOR XML 格式化 SQL Server
- python - dataframe.idxmax() - 前 N 次出现
- c# - 如何在 ASP.NET Core 中使用 XML 架构反序列化自定义 Claim.ValueType
- android-studio - 启动 Studio 时出错 - JAVA_HOME - 无法创建 JVM.JVM 路径
- swift - 使用 PDFKit 创建 PDF 文档时的共享问题
- vue.js - 使用拼接设置数据后道具发生变化
- python - 我应该在 try-except 块中添加一个 else 语句来处理 return 语句吗?
- arrays - 在 Swift 中通过 segue 传递后访问数组值的问题
- docker - 从私有 GKE 集群访问非 gcr 公共容器注册表