如何使用 read_line_to_codes & atom_codes 迭代生成行数组作为我的 .txt 文件的字符串?

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

我正在尝试使用 read_line_to_codes(Stream,Result)atom_codes(String,Result)。这两个谓词首先从文件中读取行作为字符代码数组,然后将此数组转换回字符串。然后我想将所有这些字符串输入到一个字符串数组中。

我尝试了递归方法,但在开始时如何将数组实际实例化为空,以及 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).

我希望使用递归方法将行数组获取为字符串。

遵循基于 Logtalk 的可移植 解决方案,您可以按原样与大多数 Prolog 编译器(包括 GNU Prolog)一起使用,或者适应您自己的代码:

---- 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.
-----------------------

用于测试的示例文件:

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

简单测试:

$ gplgt
...

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

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

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

yes

我觉得这个问题有很多困惑。

  • 问题被标记为 "gnu-prolog" 但 read_line_to_codes/2 不在其标准库中。
  • 你说字符串:什么意思?你能说明 the type testing predicates in GNU-Prolog, or maybe in SWI-Prolog 中的哪一个应该在那些 "strings" 上成功吗?
  • 期待一种递归方法。那是什么意思?你想要递归的方法,你必须使用递归的方法,或者你认为如果你这样做你最终会得到递归的方法?

不用递归在 SWI-Prolog 中完成,得到 strings:

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

如果您需要其他东西,您需要更好地解释它是什么。