简体   繁体   中英

reading files in Prolog

I am trying to read the file 'nouns.csv' which looks like this in notepad:

femin,femin,1,f,woman,women.
aqu,aqu,1,f,water,waters.

I have tried using this in SWI-Prolog:

18 ?- read(X).
X = end_of_file.

19 ?- see('nouns.csv').
true.

20 ?- seeing(X).
X = <stream>(000000000017F770).

21 ?- read(X).
X = end_of_file.

22 ?- 

I have absolutely no experience with Input and Output (in any language) and I am confused. I thought read(X) would return the whole file as a string (which I thought is a stream). I want to read in each line and apply this predicate to it:

nounstage(Input) -->
    ["noun("],
    [Adjust],
    [")."],
    {
         append(Adjust,[46],Input)
    }.

nounlineparse(X,Y) :-
    phrase(nounstage(X),N),
    flatten(N,Y),
    asserta(Y).

I presumed I would make a giant list of every line in the nouns.csv, then iterate through the list and apply nounlineparse to each element. How can I get my file/stream into this giant list (or is the giant list way a bad way of doing this?).

In SWI-Prolog, the easier route is library( csv ).

If you need to do specific processing on read items, library( pure_input ) can help you. The basic skeleton is like

:- use_module(library(pure_input)).
:- use_module(library(dcg/basics)).

read_csv(Path, Records) :-
    phrase_from_file(read_csv_file(Records), Path).

read_csv_file([Tokens|Lines]) -->
    read_csv_line(Tokens), read_csv_file(Lines).
read_csv_file([]) --> [].


read_csv_line([Token]) -->
    string(TokenS), ( ".\n" ; "." ), {atom_codes(Token, TokenS)} .
read_csv_line([Token|Tokens]) -->
    string(TokenS), ",", {atom_codes(Token, TokenS)}, !, read_csv_line(Tokens).

You will need to pay much attention to details...

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