导入csv文件数据以填充Prolog知识库 [英] Import csv file data to populate a Prolog knowledge base

查看:93
本文介绍了导入csv文件数据以填充Prolog知识库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件 example.csv ,其中包含标题为var1和var2的两列.

I have a csv file example.csv which contains two columns with header var1 and var2.

我想用重复的事实填充最初为空的Prolog知识库文件 import.pl ,同时将 example.csv 的每一行都视为相同:

I want to populate an initially empty Prolog knowledge base file import.pl with repeated facts, while each row of example.csv is treated same:

fact(A1, A2).
fact(B1, B2).
fact(C1, C2).

如何在SWI-Prolog中对此进行编码?

How can I code this in SWI-Prolog ?

编辑,基于@Shevliaskovic的回答:

:- use_module(library(csv)).
import:-
    csv_read_file('example.csv', Data, [functor(fact), separator(0';)]),
    maplist(assert, Data).

在控制台中运行 import.时,我们将完全按照请求的方式更新知识库(事实是,知识库是直接在内存中直接更新的,而不是通过文件并随后进行咨询.)

When import. is run in console, we update the knowledge base exactly the way it is requested (except for the fact that the knowledge base is directly updated in memory, rather than doing this via a file and subsequent consult).

检查 setof([X,Y],fact(X,Y),Z).:

Z = [['A1', 'A2'], ['B1', 'B2'], ['C1', 'C2'], [var1, var2]].

推荐答案

SWI Prolog为此提供了内置过程.

SWI Prolog has a built in process for this.

csv_read_file(+File, -Rows) 

或者您可以添加一些选项:

Or you can add some options:

csv_read_file(+File, -Rows, +Options) 

您可以在文档中看到它.有关更多信息

You can see it at the documentation. For more information

以下是该文档的示例:

假设我们要根据我们创建的CSV文件创建谓词表/6知道每条记录包含6个字段.这可以使用代码来完成以下.没有选项arity(6),这将生成一个谓词table/N,其中N是数据中每条记录的字段数.

Suppose we want to create a predicate table/6 from a CSV file that we know contains 6 fields per record. This can be done using the code below. Without the option arity(6), this would generate a predicate table/N, where N is the number of fields per record in the data.

?- csv_read_file(File, Rows, [functor(table), arity(6)]),
   maplist(assert, Rows).

例如:

如果您的File.csv如下所示:

If you have a File.csv that looks like:

A1  A2
B1  B2
C1  C2

您可以将其导入到SWI中,例如:

You can import it to SWI like:

9 ?- csv_read_file('File.csv', Data).

结果将是:

Data = [row('A1', 'A2'), row('B1', 'B2'), row('C1', 'C2')].

这篇关于导入csv文件数据以填充Prolog知识库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆