簡體   English   中英

從 prolog 中的文本文件中讀取

[英]Reading from textfile in prolog

我在讀取 GNU Prolog 中的文本文件時遇到了一些麻煩。 我想讀取 a.txt 文件並將文件移動到列表中。 我試圖按照 stackoverflow 上的一些先前示例來讀取文件,但無法訪問該文件(似乎)。 這是我到目前為止所得到的:

readFile:-
    open('text.txt', read, File),
    read_lines(File, Lines),
    close(File),
    write(Lines), nl.

read_lines(File,[]):- 
    at_end_of_stream(File).

read_lines(File,[X|L]):-
    \+ at_end_of_stream(File),
    read(File,X),
    read_lines(File,L).

當我嘗試調用時: ?- readFile. 給我一個錯誤消息: uncaught exception: error(syntax_error('text.txt:2 (char:1). or operator expected after expression'),read/2)

提前致謝!

編輯:正如大衛所提供的,GNU Prolog 的字符輸入/輸出庫和 get_char 為我工作!

工作代碼:

readFile:-
    open('text.txt', read, File),
    read_lines(File, Lines),
    close(File),
    write(Lines), nl.

read_lines(File,[]):- 
    at_end_of_stream(File).

read_lines(File,[X|L]):-
    \+ at_end_of_stream(File),
    get_char(File,X),
    read_lines(File,L).

您可以稍微改進您的編輯答案。 首先請注意read_line/2謂詞名稱具有誤導性。 您正在將文本文件讀取為字符列表,而不是單個行列表。 您還兩次調用at_end_of_stream/1謂詞,並在每次調用read_lines /2謂詞時創建一個虛假的選擇點。 此外, at_end_of_stream/1謂詞雖然是一個標准謂詞,但在所有 Prolog 系統中都沒有可靠的實現。 您的代碼的可能重寫是:

read_file(File, Chars) :-
    open(File, read, Stream),
    get_char(Stream, Char),
    read_file(Stream, Char, Chars),
    close(Stream).

read_file(Stream, Char, Chars) :-
    (   Char == end_of_file ->
        Chars = []
    ;   Chars = [Char| Rest],
        get_char(Stream, Next),
        read_file(Stream, Next, Rest)
    ).

現在您的意圖更清楚了,可以使用 Logtalk reader庫通過一次調用來完成相同的功能:

reader::file_to_chars(File, Chars)

但是,如果學習是您的主要目標,那么編寫自己的解決方案而不是依賴現有的庫是一個不錯的選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM