如何读入文本文件并将其打印到Prolog中的文件中? [英] How do I read in a text file and print them out to a file in Prolog?

查看:177
本文介绍了如何读入文本文件并将其打印到Prolog中的文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a text file, and I want to read it in and print them out in screen and write them into a new output file. So what I have done so far is

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

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

But I only received an error message like,

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

我该怎么办?

推荐答案

read/2读取有效的Prolog文本.该消息表明,在text.txt的第1行中,您有一些无效的Prolog文本.也许几个单词之间用空格隔开.

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.

如果您想阅读常规文本,则可以使用get_char/2进行非常低级的阅读,或者您可以使用语法进行高级的阅读. SWI-Prolog为此提供了library(pio).

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.

这里是Prolog程序员的等价于grep -q.

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

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

实际上是grep -c.

您需要为其加载以下定义:

You need to load following definition for it:

... --> [] | [_], ... .

这篇关于如何读入文本文件并将其打印到Prolog中的文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆