Import csv file data to populate a Prolog knowledge base

元气小坏坏 提交于 2021-01-22 08:48:45

问题


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

enter image description here

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

回答1:


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


来源:https://stackoverflow.com/questions/24095068/import-csv-file-data-to-populate-a-prolog-knowledge-base

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!