Reading files in PROLOG

Asked

Viewed 978 times

2

How can I read in PROLOG a.txt file in this way:

iago.neves pedro.santos
joao.vitor larissa.figueiredo

Being Iago Neves, a name and Pedro Santos another name, João Vitor and Larissa Figueiredo. I tried to use the read command, but it read to the point and I can’t read the surnames along with the names correctly. Someone, please?

1 answer

1

The command read/1 serves to read terms of a file with the same syntax as Prolog. To read arbitrary content (i.e. strings) you will need the methods of primitive character reading, such as the get_char/1. An example (without going into the file coding merit, which I assume you already specified when opening the stream input) would be:

ler_chars(S) :-
    get_char(C),
    ler_resto(C,S).

ler_resto(end_of_file, []).
ler_resto(C, [C|R]) :-
    get_char(C2),
    ler_resto(C2, R).

After calling ler_chars in a stream, your content will be returned in a character list. If you want this content in a string, just call atom_chars/2 in the result:

?- abrir_stream, ler_chars(Chars), atom_chars(String, Chars).

But a better option is to interpret the contents of that file through a DCG grammar. From what I understand, you have a series of names separated by spaces or line breaks, right? And each name consists of nome.sobrenome. That expressed in DCG would be:

nomes([]) --> [].
nomes([Nome|R]) --> nome(Nome), [' '], nomes(R).
nomes([Nome|R]) --> nome(Nome), ['\n'], nomes(R).
nomes([Nome]) --> nome(Nome).

nome(pessoa(Nome,Sobrenome)) --> palavra(CNome), ['.'], palavra(CSobrenome),
                                 { atom_chars(Nome, CNome),
                                   atom_chars(Sobrenome, CSobrenome) }.

palavra([]) --> [].
palavra([C|R]) --> [C], { is_alpha(C) }, palavra(R).

Calling this code in the read result produces a list where each element is of the form pessoa(Nome,Sobrenome):

?- abrir_stream, ler_chars(Chars), nomes(Pessoas, Chars, []).

Pessoas = [pessoa(iago, neves), pessoa(pedro, santos), pessoa(joao, vitor), pessoa(larissa, figueiredo)]

Example in the ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.