2014-05-11 23 views
1

我不得不使用一些SWI-Prolog代碼來打開一個新的流(它在文件系統上創建一個文件)並向其中注入一些數據。生成的文件將在代碼中的其他位置讀取。序言中的字符串流?

我想在Prolog中用字符串流替換文件流,以便不創建任何文件,然後讀取放入流中的所有內容作爲一個大字符串。

SWI-Prolog有串流嗎?如果是這樣,我怎麼能用它們來完成這項任務?如果您能提供一小段代碼,我將非常感激。謝謝!

回答

1

SWI-Prolog執行memory mapped files。下面是從我的一些舊的代碼片斷,做兩個寫/讀

%% html2text(+Html, -Text) is det. 
% 
% convert from html to text 
% 
html2text(Html, Text) :- 
    html_clean(Html, HtmlDescription), 
    new_memory_file(Handle), 
    open_memory_file(Handle, write, S), 
    format(S, '<html><head><title>html2text</title></head><body>~s</body></html>', [HtmlDescription]), 
    close(S), 
    open_memory_file(Handle, read, R, [free_on_close(true)]), 
    load_html_file(stream(R), [Xml]), 
    close(R), 
    xpath(Xml, body(normalize_space), Text). 
+0

這正是我想到的!謝謝! –

0

另一種選擇是使用with_output_to/2具有組合current_output/1:

write_your_output_to_stream(Stream) :- 
    format(Stream, 'example output\n', []), 
    format(Stream, 'another line', []). 

str_out(Codes) :- 
    with_output_to(codes(Codes), (
     current_output(Stream), 
     write_your_output_to_stream(Stream) 
    )). 

用例:

?- portray_text(true), str_out(C). 
C = "example output 
another line" 

當然,您可以選擇重定向輸出到原子,字符串,代碼列表(如上例所示)等,只需使用相應的參數即可with_output_to/2:

with_output_to(Atom(凌),...)

with_output_to(string(String), ...) 
with_output_to(codes(Codes), ...) 
with_output_to(chars(Chars), ...) 

見with_output_to/2文件:

http://www.swi-prolog.org/pldoc/man?predicate=with_output_to/2

後來,你可以使用open_string/2,open_codes_stream/2和類似的謂詞來打開字符串/代碼列表作爲輸入流來讀取數據。