任务:将源文件中包含指定字符串的所有行作为片段写入新文件,该片段是从键盘输入的。
我不知道如何将Prolog中来自文件的行逐行与我从键盘输入的片段进行比较,并将匹配的行输出到新文件中。我将很高兴收到任何建议或指导。我不能在开场白中直接思考。
f:-
write('Enter the name of the source file:'),
read(SOURFILE),
check_exist(SOURFILE),
open(SOURFILE,read,FROM),
read_line_to_string(FROM,X),writef(" "),
writef(X),
writeln(" "),
write('Enter a substring:'),
read(WR),
close(FROM),
write('Enter the name of the new file:'),
read(NEWFILE),
check_exist(NEWFILE),
name(S,X),
write_to_file(NEWFILE,S).
check_exist(Filename):-exists_file(Filename),!.
check_exist(_):-writeln('There is no such file'),
fail.
write_to_file(Filename,TEXT) :-
open(Filename, write, File),
write(File, TEXT),nl,
writeln('Data recorded successfully'),
close(File).发布于 2021-03-28 22:09:20
在SWI-Prolog中,您可以使用谓词sub_string/5来验证字符串是否包含子字符串。因此,要解决您的问题,您可以这样做:
copy(From, To, Substring) :-
open(From, read, Input),
open(To, write, Output),
repeat,
read_line_to_string(Input, String),
( String = end_of_file
-> ! % stop reading lines
; sub_string(String, _, _, _, Substring),
writeln(Output, String),
fail ), % backtracks to read next line
close(Input),
close(Output).https://stackoverflow.com/questions/66840573
复制相似问题