2

Possible Duplicate:
Read a file line by line in Prolog

I found the following prolog code which reads one character at a time and prints out.

process(File) :-
        open('C:/Users/BHARAT/Desktop/a.txt', read, In),
        get_char(In, Char1),
        process_stream(Char1, In),
        close(In).

process_stream(end_of_file, _) :- !.
process_stream(Char, In) :-
        print(Char),
        get_char(In, Char2),
        process_stream(Char2, In).

But if the file has multiple lines is there a way to read 1 whole line at a time so that it will be easy for tokenizing.

4

2 回答 2

5

你说你想对输入进行标记 - 最好的方法是确定子句语法(DCG)。在library(pio)SWI 中,您可以直接使用语法读取文件,如下所示:

?- use_module(library(pio)).
?- phrase_from_file(seq(Xs),f).

seq([]) --> [].
seq([E|Es]) --> [E], seq(Es).

seq//1现在用一些更精细的标记器替换。

于 2011-11-22T18:43:34.817 回答
2

SWI-Prolog 有一些支持谓词,例如:

..., read_line_to_codes(Stream, Codes), phrase(parse, Codes, []), ...

但我会建议你采用phrase_from_file/2(正如另一个答案中已经建议的那样)。有一个支持库来帮助解析输入,还有一些现成的解析器:

:- use_module(library(http/dcg_basics)).

编辑支持库已重命名,有一个向后兼容技巧,允许旧命名,但现在最好使用库(dcg/basics)。

于 2011-11-22T20:31:57.687 回答