Chits
Chits

Reputation: 23

Amzi Prolog Tokenize

I would want to read a file and store the words in every line as a list. This is my code:

main :-
open('sample.txt', read, Str),
read_file(Str,Lines),
close(Str),
write(Lines), nl.

read_file(Stream,[]) :-
at_end_of_stream(Stream).

append1([H|T],Old_list,New_list):-
New_List = [H|Old_list],
write(New_List),
append1(T,New_List,New_list).

read_file(Stream,[X|L]) :-
\+ at_end_of_stream(Stream),
read(Stream,X),
write(X),
append1(X,[],New_List),
read_file(Stream,L).

I realise that X is a term here but I am not able to get my program working.

Input : 'Australia', 'Singapore','23','34','Mon/Tue'.
Output : New_List=[Australia,Singapore,23,34,Mon/Tue].

I am using Amzi prolog btw!

Thanks in advance for the help!

Upvotes: 0

Views: 445

Answers (1)

hardmath
hardmath

Reputation: 8823

The ISO predicate read/2 inputs Prolog terms and requires the input to be terminated by a period. You can try this interactively from the query prompt.

But likely what you want is not to read Prolog terms but rather to read an entire input line as a string and then tokenize that into "words" that are items in a list.

For this purpose Amzi! Prolog has several non-ISO predicates that could be useful. See the documentation here for read_string/2, and see also the documentation for string_split/3 and for string_tokens/3.

One or the other of these latter two predicates is apt to be more useful, depending on what you want to do about whitespace and punctuation in your lists of "words".

Upvotes: 1

Related Questions