1

我有一个文本文件,我想将其读入并在屏幕上打印出来并将它们写入一个新的输出文件。所以到目前为止我所做的是

main :-
    open('text.txt', read, ID),  % open a stream
    repeat,             % try again forever
    read(ID, X),        % read from the stream
    write(X), nl,       % write to current output stream
    X == end_of_file,   % fail (backtrack) if not end of 
    !,
    close(ID).

但我只收到一条错误消息,例如,

ERROR: text.txt:1:0: Syntax error: Operator expected

我应该怎么办?

4

3 回答 3

2

read/2 reads valid Prolog text. The message suggests, that in line 1 of text.txt you have some invalid Prolog text. Maybe a couple of words separated by spaces.

If you want to read regular text, you can do it very low-level using get_char/2, or you might want to do it more high level using grammars. SWI-Prolog has library(pio) for that.

Here is the Prolog programmer's equivalent to grep -q.

?- phrase_from_file((...,"root",...),'/etc/passwd').
true ;
true ;
true ;
false.

Actually, that's rather grep -c.

You need to load following definition for it:

... --> [] | [_], ... .
于 2011-11-12T22:51:43.377 回答
1

如果你想要一个可重用的片段:

%%  file_atoms(File, Atom) is nondet.
%
%   read each line as atom on backtrack
%
file_atoms(File, Atom) :-
    open(File, read, Stream),
    repeat,
    read_line_to_codes(Stream, Codes),
    (   Codes \= end_of_file
    ->  atom_codes(Atom, Codes)
    ;   close(Stream), !, fail
    ).

这调用 read_line_to_codes,一个内置的 SWI-Prolog。

于 2011-11-14T16:28:34.297 回答
0
is_eof(FlHndl, CharCode, CurrentLine, FileAkku, FileContent) :-
        CharCode == -1,
        append(FileAkku, [CurrentLine], FileContent),
        close(FlHndl), !.

is_newline(FlHndl, CharCode, CurrentLine, FileAkku, FileContent) :-
        CharCode == 10,
        append(FileAkku, [CurrentLine], NextFileAkku),
        read_loop(FlHndl, '', NextFileAkku, FileContent).

append_char(FlHndl, CharCode, CurrentLine, FileAkku, FileContent) :-
        char_code(Char, CharCode),
        atom_concat(CurrentLine, Char, NextCurrentLine),
         read_loop(FlHndl, NextCurrentLine, FileAkku, FileContent).

read_file(FileName, FileContent) :-
        open(FileName, read, FlHndl),
        read_loop(FlHndl, '', [], FileContent), !.

read_loop(FlHndl, CurrentLine, FileAkku, FileContent) :-
        get_code(FlHndl, CharCode),
        ( is_eof(FlHndl, CharCode, CurrentLine, FileAkku, FileContent)
        ; is_newline(FlHndl, CharCode, CurrentLine, FileAkku, FileContent)
        ; append_char(FlHndl, CharCode, CurrentLine, FileAkku, FileContent)).

main(InputFile, OutputFile) :-
    open(OutputFile, write, OS),
    (   read_file(InputFile,InputLines),
        member(Line, InputLines),
        write(Line), nl,
        write(OS,Line),nl(OS),
        false
        ;
        close(OS)
    ).

所以,你可以像这样使用它main('text.txt', 'output.txt').

于 2011-11-12T22:55:20.713 回答