How to use read_line_to_codes & atom_codes iteratively to generate array of lines as strings of my .txt file?

喜你入骨 提交于 2019-12-13 04:44:41

问题


I am trying to use read_line_to_codes(Stream,Result) and atom_codes(String,Result). These two predicates first, read line from file as an array of char codes, and then convert this array back to string. Then I would like to input all those strings to an array of Strings.

I tried the recursive approach but have trouble with how to actually instantiate the array to empty in the beginning, and what would be the terminating condition of process_the_stream/2.

/*The code which doesn't work.. but the idea is obvious.*/

process_the_stream(Stream,end_of_file):-!.
process_the_stream(Stream,ResultArray):-
        read_line_to_codes(Stream,CodeLine),
        atom_codes(LineAsString,CodeLine),
        append_to_end_of_list(LineAsString,ResultArray,TempList),
        process_the_stream(Stream,TempList).

I expect a recursive approach to get array of lines as strings.


回答1:


Follows a Logtalk-based portable solution that you can use as-is with most Prolog compilers, including GNU Prolog, or adapt to your own code:

---- processor.lgt ----
:- object(processor).

    :- public(read_file_to_lines/2).

    :- uses(reader, [line_to_codes/2]).

    read_file_to_lines(File, Lines) :-
        open(File, read, Stream),
        line_to_codes(Stream, Codes),
        read_file_to_lines(Codes, Stream, Lines).

    read_file_to_lines(end_of_file, Stream, []) :-
        !,
        close(Stream).
    read_file_to_lines(Codes, Stream, [Line| Lines]) :-
        atom_codes(Line, Codes),
        line_to_codes(Stream, NextCodes),
        read_file_to_lines(NextCodes, Stream, Lines).

:- end_object.
-----------------------

Sample file for testing:

------ file.txt -------
abc def ghi
jlk mno pqr
-----------------------

Simple test:

$ gplgt
...

| ?- {library(reader_loader), processor}.
...

| ?- processor::read_file_to_lines('file.txt', Lines).

Lines = ['abc def ghi','jlk mno pqr']

yes



回答2:


I sense a lot of confusion in this question.

  • The question is tagged "gnu-prolog" but read_line_to_codes/2 is not in its standard library.
  • You talk about strings: what do you mean? Can you show which one of the type testing predicates in GNU-Prolog, or maybe in SWI-Prolog should succeed on those "strings"?
  • You expect a recursive approach. What does that mean? You want a recursive approach, you must use a recursive approach, or you think that if you did it you would end up with a recursive approach?

To do it in SWI-Prolog without recursion, and get strings:

read_string(Stream, _, Str), split_string(Str, "\n", "\n", Lines)

If you need something else you need to explain better what it is.



来源:https://stackoverflow.com/questions/55365567/how-to-use-read-line-to-codes-atom-codes-iteratively-to-generate-array-of-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!