I wanted to read from a file and then store it in the form of list. Every time there is a comma,it will combine all the characters before the comma to form a new word. A new line will indicate it is a new sub-list. It is very similar to what java can do when they read a file. I am learning prolog and having issue with reading file and getting them as input to perform different operations. Do you know any methods that can help me read a file and use those data as input for different functions? Thank you.
Read File:
Thales,Olivia,Jackson,Sophia
Canada Post,Sophia,Jackson,Olivia
Cisco,Olivia,Sophia,Jackson
Code:
read_from_file(File, A):-
open(File, read, Stream),
get_char(Stream, Char1),
process_the_stream(Char1, Stream, A),
close(Stream).
write_on_file(File,Text):-
open(File, append, Stream),
write(Stream, Text), nl,
close(Stream).
process_the_stream(end_of_file, _, []):- !.
process_the_stream(Char, Stream, [Char|B]):-
write(Char),
get_char(Stream, Char2),
process_the_stream(Char2, Stream, B).
Current output:
A = ['T',h,a,l,e,s,',','O',l,i,v,i,a,',','J',a,c,k,s,o,n,',','S',o,p,h,i,a,'\n','C',a,n,a,d,a,' ','P',o,s,t,',','S',o,p,h,i,a,',','J',a,c,k,s,o,n,',','O',l,i,v,i,a,'\n','C',i,s,c,o,',','O',l,i,v,i,a,',','S',o,p,h,i,a,',','J',a,c,k,s,o,n]
Desire Output:
A = [[Thales, Olivia, Jackson, Sophia], [Canada Post, Sophia, Jackson, Olivia], [Cisco, Olivia, Sophia, Jackson]]