导入 csv 文件数据以填充 Prolog 知识库

use*_*503 5 csv prolog swi-prolog

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

在此处输入图片说明

我想import.pl用重复的事实填充最初为空的 Prolog 知识库文件,而每一行的example.csv处理方式相同:

fact(A1, A2).
fact(B1, B2).
fact(C1, C2).
Run Code Online (Sandbox Code Playgroud)

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

编辑,基于@Shevliaskovic 的回答

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

import.在控制台中运行时,我们完全按照请求的方式更新知识库(除了知识库直接在内存中更新,而不是通过文件和后续咨询来更新)。

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

Z = [['A1', 'A2'], ['B1', 'B2'], ['C1', 'C2'], [var1, var2]].
Run Code Online (Sandbox Code Playgroud)

She*_*vic 5

SWI Prolog 有一个内置的过程。

这是

csv_read_file(+File, -Rows) 
Run Code Online (Sandbox Code Playgroud)

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

csv_read_file(+File, -Rows, +Options) 
Run Code Online (Sandbox Code Playgroud)

您可以在文档中看到它。想要查询更多的信息

这是文档中的示例:

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).
Run Code Online (Sandbox Code Playgroud)

For example:

If you have a File.csv that looks like:

A1  A2
B1  B2
C1  C2
Run Code Online (Sandbox Code Playgroud)

You can import it to SWI like:

9 ?- csv_read_file('File.csv', Data).
Run Code Online (Sandbox Code Playgroud)

The result would be:

Data = [row('A1', 'A2'), row('B1', 'B2'), row('C1', 'C2')].
Run Code Online (Sandbox Code Playgroud)

  • @user2030503 我添加了一个例子。这对你有帮助吗? (2认同)