如何在 OCaml 中下载、解压缩和处理 gzip 文件?

How can I download, uncompress and process a gzip file in OCaml?

我希望我的 ocaml 应用程序直接下载、解压缩 (gzip),然后逐行处理生成的文本文件,而不使用临时文件和外部程序。

我查看的库是 cohttpocurlcamlzip。不幸的是,我没有找到让它们协同工作的好方法。

OCaml 的实现方式是什么?

您可以使用管道和线程使 ocurlcamlzip 一起工作。概念验证:

#use "topfind";;
#thread;;
#require "unix";;
#require "curl";;
#require "zip";;

let () = Curl.(global_init CURLINIT_GLOBALALL)

let download url oc =
  let open Curl in
  let h = init () in
  setopt h (CURLOPT_URL url);
  setopt h (CURLOPT_WRITEFUNCTION (fun x -> output_string oc x; String.length x));
  perform h;
  cleanup h

let read_line really_input =
  let buf = Buffer.create 256 in
  try
    while true do
      let x = " " in
      let () = really_input x 0 1 in
      if x = "\n" then raise Exit else Buffer.add_string buf x;
    done;
    assert false
  with
  | Exit -> Buffer.contents buf
  | End_of_file -> if Buffer.length buf = 0 then raise End_of_file else Buffer.contents buf

let curl_gzip_iter f url =
  let ic, oc = Unix.pipe () in
  let ic = Unix.in_channel_of_descr ic and oc = Unix.out_channel_of_descr oc in
  let t = Thread.create (fun () -> download url oc; close_out oc) () in
  let zic = Gzip.open_in_chan ic in
  let zii = Gzip.really_input zic in
  let () =
    try
      while true do
        let () = f (read_line zii) in ()
      done;
      assert false
    with
    | End_of_file -> ()
  in
  Gzip.close_in zic;
  Thread.join t

let () = curl_gzip_iter print_endline "file:///tmp/toto.gz"

不过,当一个人必须处理错误时,它变得很痛苦。

如果您想完成工作,我会放弃“无外部程序”要求并编写 OCaml 源代码文件 download_gunzip_lines.ml:

open Printf

let read_all_lines ic =
  Seq.unfold (fun () -> try Some(input_line ic, ()) with _ -> None) ()

let () =
  match Sys.argv with
  | [|_; url|] ->
    read_all_lines(Unix.open_process_in(sprintf "wget -q -O - %s | gunzip" url))
    |> Seq.iter (fun line -> printf "%d\n" (String.length line))
  | _ -> eprintf "Usage: download_gunzip_lines <url>"

使用 dune 文件:

(executable
 (name download_gunzip_lines)
 (libraries unix))

然后:

dune build --profile release

构建它并:

./_build/default/download_gunzip_lines.exe http://www.o-bible.com/download/kjv.gz

到 运行 它在 King James 圣经的副本上。

更好的是,运行 wgetgunzip 使用来自 Bash 脚本的 OCaml 代码,只需处理 OCaml 中的行。