简体   繁体   中英

Import csv file data to populate a Prolog knowledge base

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

在此输入图像描述

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).

How can I code this in SWI-Prolog ?

EDIT, based on answer from @Shevliaskovic :

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

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).

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

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

SWI Prolog has a built in process for this.

It is

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

Here is the example that the documentation has:

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).

For example:

If you have a File.csv that looks like:

A1  A2
B1  B2
C1  C2

You can import it to SWI like:

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

The result would be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM