Prolog I/O读取文件并提取信息以供使用 [英] Prolog I/O reading file and extracting info to use
问题描述
在Prolog旅途中,现在我迷上了I/O部件.我试图读取以特定格式编写的文件,并使用它们创建我的事实并使用这些事实.但是在阅读了stackoverflow中的几个库和示例之后,我仍然无法找到答案.例如,这是我的文件.
During my journey in Prolog, now I am stuck with i/o part. I was trying to read a file which is written in a specific format and create my facts with them and use these facts. But after reading several libraries and examples in stackoverflow, I could not manage to come up an answer though. For example, this is my file.
a,b,c,d,e
funct(a,[1,2,3,4,5])
funct(b,[2,4,6,8,10]
funct(c,[1,3,5,7,9])
funct(d,[1,1,2,3,5])
funct(e,[3,7,11,19,23])
funct/2具有在第一行中写入的每个元素的列表.我尝试在开始时获得第一行然后使用它,但是我无法做到这一点.我认为这是正确的方法,尽管在尝试Prolog之后我现在不能确定自己了.我想做的是这样的:
funct/2 has list in terms of every element which is written in first line. I tried to get first line at the beginning then use it, but I could not manage to do it. I think it is the right way, although after trying Prolog now I cannot be so sure of myself. What I am trying to do is this:
functExp(a,a,1)
functExp(a,b,2)
functExp(a,c,3)
functExp(a,d,4)
functExp(a,e,5)
functExp(a,b,1)
functExp(b,a,2)
functExp(b,b,4)
functExp(b,c,6)...
我正在使用SWI-Prolog btw.
I am using SWI-Prolog btw.
很抱歉给您带来不便.我不知道尝试使用功能"是错误的.我纠正了我的期望. functExp/3是我想要获得的输出,它与funct不同.我认为我应该使用assert/assertz内置函数,但我仍然不确定应该怎么做,同样,我为我的误会感到非常抱歉.您可能猜到我还是个新手,所以如果您忍受我将不胜感激.
Edit : Sorry for inconvience. I had no idea that trying to use "funct" is wrong. I corrected what I expect. functExp/3 is the output I'm trying to get and its different from funct.I think I should use assert/assertz built-in function but I am still not sure what I should do.Again I'm so sorry for my misunderstanding. I'm still a newbie as you may guess, so I would be appreciated if you an bear with me.
推荐答案
SWI-Prolog具有大量的IO内置函数,将它们组合在一起,我们可以轻松读取您的文件数据:
SWI-Prolog has plenty of IO builtins, combining them we can read easily your file data:
process_file :-
open('input.txt', read, S),
read_line_to_codes(S, Fs),
atom_codes(Fa, Fs),
atomic_list_concat(Elems, ',', Fa),
repeat,
read_line_to_codes(S, L),
read_from_codes(L, T),
( T == end_of_file -> close(S)
; apply_line(T, Elems), fail
).
apply_line(T, Es) :-
T =.. [F,K,As],
maplist(out_line(F, K), Es, As).
out_line(F, K, E, A) :-
T =.. [F, K, E, A],
writeln(T).
input.txt当然包含您显示的数据
input.txt of course contains the data you show
这篇关于Prolog I/O读取文件并提取信息以供使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!