如何读入文本文件并将其打印到 Prolog 中的文件中?
我有一个文本文件,我想读入它并在屏幕上打印它们并将它们写入新的输出文件。所以到目前为止我所做的是
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
我应该做什么?
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
What should I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
read/2
读取有效的 Prolog 文本。该消息表明,在 text.txt 的第 1 行中,您有一些无效的 Prolog 文本。也许是几个用空格分隔的单词。如果您想阅读常规文本,您可以使用
get_char/2
进行非常低级的操作,或者您可能想使用语法进行更高级别的操作。 SWI-Prolog 有用于此目的的library(pio)
。这是 Prolog 程序员相当于
grep -q
的命令。实际上,这更像是
grep -c
。您需要为其加载以下定义:
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 haslibrary(pio)
for that.Here is the Prolog programmer's equivalent to
grep -q
.Actually, that's rather
grep -c
.You need to load following definition for it:
如果您想要一个可重用的代码片段:
这将调用 read_line_to_codes,一个 SWI-Prolog 内置函数。
If you want a reusable snippet:
This calls read_line_to_codes, a SWI-Prolog builtin.
因此,您可以像
main('text.txt', 'output.txt') 一样使用它。
So, you can use it like
main('text.txt', 'output.txt').