在 Prolog 中逐行读取文件 [英] Read a file line by line in Prolog

查看:27
本文介绍了在 Prolog 中逐行读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取纯文本文件并将谓词应用于每一行(谓词包含执行输出的 write).我该怎么做?

I'd like to read a plain text file and apply a predicate to each line (the predicates contain write which does the output). How would I do that?

推荐答案

在 SWI-Prolog 中,最简洁的解决方案是编写一个 DCG 来描述行"是什么,然后为每一行调用一个谓词.使用 library(pio) 将 DCG 应用于文件.

In SWI-Prolog, the cleanest solution is to write a DCG that describes what a "line" is, then call a predicate for each line. Use library(pio) to apply the DCG to a file.

编辑:根据要求,考虑:

:- use_module(library(pio)).

lines([])           --> call(eos), !.
lines([Line|Lines]) --> line(Line), lines(Lines).

eos([], []).

line([])     --> ( "
" ; call(eos) ), !.
line([L|Ls]) --> [L], line(Ls).

示例用法:?- phrase_from_file(lines(Ls), 'your_file.txt').

这篇关于在 Prolog 中逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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