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



我正在尝试使用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不在其标准库中。
  • 说的是字符串:你是什么意思?你能证明GNU-Prolog中的哪一个类型测试谓词,或者SWI-Prolog中的哪一个应该在这些"字符串"上成功吗?
  • 期望采用递归方法。那是什么意思?你想要一个递归的方法,你必须使用递归方法,或者你认为如果你这样做了,你最终会得到一个递归方法?

要在没有递归的情况下在SWI-Prolog中执行此操作,并获取字符串

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

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

最新更新