我有以下格式的輸入文件:如何從ocaml中的文件讀取?
q0;q1
a;b
(q0,x);(q1;x)
我想有三個列表如下:
a = ["q0";"q1"];
b = ["a";"b"];
c = [("q0","x");("q1","y")];
這裏是我的代碼:
let buf = Queue.create();;
let catfile filename =
let rec print_all_lines in_chan =
Queue.add (input_line in_chan) buf;
print_all_lines in_chan
in
let in_file = open_in filename in
try
print_all_lines in_file
with End_of_file -> close_in in_file;;
catfile "test.txt";;
let rec pvt_rec_split skipf rv str c i limit =
if (List.length rv < (limit - 1)) && (i < String.length str) then (
if String.contains_from str i c then
let o = String.index_from str i c in
pvt_rec_split skipf
(rv @ [ String.sub str i (o - i)])
str c
(skipf str c o)
limit;
else
rv @ [ String.sub str i ((String.length str) - i) ]
) else (
if i < String.length str then
rv @ [ String.sub str i ((String.length str) - i) ]
else
rv
);;
let split s c limit =
let rec pvt_skip_char s c i =
if (i >= String.length s) then (
String.length s
) else (
if ((String.get s i) == c) then (
pvt_skip_char s c (i +1)
) else (
i
)
)
in
pvt_rec_split pvt_skip_char [] s c 0 limit ;;
let a = split (Queue.take buf) ';' 100;;
let b = split (Queue.take buf) ';' 100;;
let c = split (Queue.take buf) ';' 100;;
基本上拆分功能拆分帶分隔符的字符串並返回一個列表。
所以,我能夠正確生成列表a和b。
但是在List c的情況下,我得到一個類型字符串列表。其實我想要一個帶有類型('string *'字符串)的列表。
我該怎麼做?
基本IO功能在[Pervasives](http://caml.inria.fr/pub/docs/manual-ocaml /libref/Pervasives.html)模塊。例如,您可以用'read_line'來讀取一行。我想,你必須展示你已經試圖獲得更好的建議。 –