我想处理文件“persons.txt”中存在的数据。 但我已经尝试了一切来处理文本文件中的所有行。
我处理数据的唯一方法是手动创建列表。
let myList = ["John"; "23"]
我希望程序迭代文本文件的所有行。 我已经设法将文本文件的所有内容传递到列表中,但我似乎无法从该阶段继续前进。
我的想法是:
你能指导我吗?
谢谢!!
open Printf
(* FILE CONTENTS *)
(*
John;23;
Mary;16;
Anne;21;
*)
let file = "data/persons.txt"
;;
(* READ FROM EXTERNAL FILE *)
let read_lines name : string list =
if Sys.file_exists (name) then
begin
let ic = open_in name in
try
let try_read () =
try Some (input_line ic)
with End_of_file -> None
in
let rec loop acc =
match try_read () with
| Some s -> loop (s :: acc)
| None -> close_in_noerr ic; List.rev acc
in
loop []
with
e -> close_in_noerr ic;[]
end
else
[]
;;
(...)
你的问题根本不明确。以下是一些观察结果:
首先,您的
read_lines
函数不会以您需要的形式返回输入。
read_lines
返回的内容如下所示:
["John;23;"; "Mary;16;"; "Anne;21;"]
但是你想要的更像是这样的:
[(“约翰”,“23)”; (“玛丽”,“16”); (“安妮”,“21”)]
这里的关键是使用
;
作为分隔符将字符串分成几部分。您可以使用 String.split_on_char
来实现此目的。
其次,您没有定义一个函数来根据参数计算答案。相反,您的计算基于全局变量。这不能一概而论。
而不是这样说:
let adult_check_condition =
... using global age and name ...
你需要定义一个函数:
let adult_check_condition age name =
... use parameters age and name ...
然后你可以用不同的年龄和名字来调用这个函数。