例如,我有一个包含10个文本字符串的txt文件。如何使用erlang读取此文本的前5个字符串?
谢谢。
发布于 2011-02-05 14:07:55
您可能需要启用缓冲的file:open/2和file:read_line/1的组合。
一首押韵诗:
$ cat mary_lamb.txt
Mary had a little lamb,
little lamb, little lamb,
Mary had a little lamb,
whose fleece was white as snow.
And everywhere that Mary went,
Mary went, Mary went,
and everywhere that Mary went,
the lamb was sure to go.源文件:
$ cat ./read_n_lines.erl
-module(read_n_lines).
-export([read_n_lines/2]).
read_n_lines(Filename,NumLines) ->
{ok, FileDev} = file:open(Filename,
[raw, read, read_ahead]),
Lines = do_read([],FileDev, NumLines),
file:close(FileDev),
Lines.
do_read(Lines, _, 0) ->
lists:reverse(Lines);
do_read(Lines, FileDev, L) ->
case file:read_line(FileDev) of
{ok, Line} ->
do_read([Line|Lines], FileDev, L - 1);
eof ->
do_read(Lines, FileDev, 0)
end.传递给file:open/2的Modes中的raw允许更快地访问文件,因为不需要任何Erlang进程来处理文件。
示例运行:
$ erl
1> c(read_n_lines).
{ok,read_n_lines}
2> Lines = read_n_lines:read_n_lines("./mary_lamb.txt", 5).
["Mary had a little lamb,\n","little lamb, little lamb,\n",
"Mary had a little lamb,\n",
"whose fleece was white as snow.\n",
"And everywhere that Mary went,\n"]
3> length(Lines).
5
4> read_n_lines:read_n_lines("./mary_lamb.txt", 666).
["Mary had a little lamb,\n","little lamb, little lamb,\n",
"Mary had a little lamb,\n",
"whose fleece was white as snow.\n",
"And everywhere that Mary went,\n",
"Mary went, Mary went,\n",
"and everywhere that Mary went,\n",
"the lamb was sure to go."]
5> 要从字符串中删除换行符,可以使用string:strip/1,2,3
5> lists:map(fun(X) -> string:strip(X, right, $\n) end, Lines).
["Mary had a little lamb,","little lamb, little lamb,",
"Mary had a little lamb,",
"whose fleece was white as snow.",
"And everywhere that Mary went,"]
6>发布于 2011-02-09 02:01:55
另一种解决方案,n_times可以在其他地方使用:
-module(n_times).
-export([test/0]).
test() ->
io:format("~p~n", [n_lines("n_times.erl", 5)]).
n_lines(FileName, N) ->
{ok, FileDev} = file:open(FileName, [raw, read, read_ahead]),
try
n_times(fun() -> {ok, L} = file:read_line(FileDev), L end, N)
after
file:close(FileDev)
end.
n_times(F, N) ->
n_times(F, N, []).
n_times(_, 0, A) ->
lists:reverse(A);
n_times(F, N, A) ->
n_times(F, N-1, [F()|A]).https://stackoverflow.com/questions/4905247
复制相似问题