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

问题描述 投票:0回答:2

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

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

我期望一种递归方法将行数组作为字符串。

prolog gnu-prolog
2个回答
2
投票

遵循基于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

0
投票

我在这个问题上感到很困惑。

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.