gpt4 book ai didi

file - Erlang 从文件中读取前 5 行

转载 作者:行者123 更新时间:2023-12-04 13:54:59 29 4
gpt4 key购买 nike

例如,我有一个包含 10 个文本字符串的 txt 文件。如何使用 erlang 读取此文本的前 5 个字符串?

谢谢你。

最佳答案

可能你想要 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.
raw , 在 Modes ,传递给 file:open/2 , 允许更快地访问文件,因为不需要 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>

关于file - Erlang 从文件中读取前 5 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4905247/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com