Reading files in PROLOG

2

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

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 using the read command, but it read to the point and I can not read the surnames along with the names correctly. Someone, please?

    
asked by anonymous 26.05.2015 / 19:55

1 answer

1

The command read/1 serves to read terms > of a file with the same Prolog syntax. To read arbitrary content (ie strings) you will need the methods of reading primitive characters , like for example get_char/1 . An example (without going into the merit of file encoding, which I assume you've already specified when opening the input stream) 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 , its contents will be returned in a list of characters. If you want this content in a string, just call atom_chars/2 in the result: / p>

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

But a better option is to interpret the contents of this 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 . This expressed in DCG would look like:

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 reading result gives you 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 on ideone.

    
26.05.2015 / 20:36