I/O 使用 Erlang,尝试将输入文件放入列表
I/O with Erlang, trying to get input file into list
-module(test).
-export([run/1]).
open_file(FileName, Mode) ->
{ok, Device} = file:open(FileName, [Mode, binary]), Device.
close_file(Device) ->
ok = file:close(Device).
read(File) ->
case file:read_line(File) of
{ok, Data} -> [Data | read(File)];
eof -> []
end.
run(InputFileName) ->
Device = open_file(InputFileName, read),
Data = read(Device),
[First |TheRest] = Data,
io:format("First line is ~p ~n", [First]),
close_file(Device).
原文件
d1 and is program program the
d2 a apply copyleft free free freedom
d3 copyleft copyleft share share users
d4 released software works
d5 licenses licenses licenses licenses licenses software
d8 apply
不知何故变成了
50> test:run("input.txt").
First line is <<"d1\tand\tis\tprogram\tprogram\tthe\n">>
ok
这是表示列表的特殊方式吗?还是我需要使用某种模块将读取的内容转换为列表?
我的最终目标是用列表制作密钥对:
{d1 [and is program program the]}
谢谢!
您从文件中读取的数据表示为二进制,而不是字符串,因为您在打开文件时指定了 binary
模式:
{ok, Device} = file:open(FileName, [Mode, binary]), Device.
如果将其更改为:
{ok, Device} = file:open(FileName, [Mode]), Device.
你的结果变成:
First line is "d1 and is program program the\n"
要获得最终结果,请将 read/1
函数更改为:
read(File) ->
case file:read_line(File) of
{ok, Data} ->
[First|Rest] = string:tokens(Data, " \t\n"),
[{First,string:join(Rest, "\t")} | read(File)];
eof -> []
end.
进行此更改后,您的程序会打印:
First line is {"d1","and\tis\tprogram\tprogram\tthe"}
其中第二个元素是一个字符串,其中的标记与原始数据中一样以制表符分隔。如果您希望第一个元素 "d1"
成为一个原子 d1
(我无法从您的问题中确定这是否是您想要的),您可以将其转换为 list_to_atom/1
.
-module(test).
-export([run/1]).
open_file(FileName, Mode) ->
{ok, Device} = file:open(FileName, [Mode, binary]), Device.
close_file(Device) ->
ok = file:close(Device).
read(File) ->
case file:read_line(File) of
{ok, Data} -> [Data | read(File)];
eof -> []
end.
run(InputFileName) ->
Device = open_file(InputFileName, read),
Data = read(Device),
[First |TheRest] = Data,
io:format("First line is ~p ~n", [First]),
close_file(Device).
原文件
d1 and is program program the
d2 a apply copyleft free free freedom
d3 copyleft copyleft share share users
d4 released software works
d5 licenses licenses licenses licenses licenses software
d8 apply
不知何故变成了
50> test:run("input.txt").
First line is <<"d1\tand\tis\tprogram\tprogram\tthe\n">>
ok
这是表示列表的特殊方式吗?还是我需要使用某种模块将读取的内容转换为列表?
我的最终目标是用列表制作密钥对:
{d1 [and is program program the]}
谢谢!
您从文件中读取的数据表示为二进制,而不是字符串,因为您在打开文件时指定了 binary
模式:
{ok, Device} = file:open(FileName, [Mode, binary]), Device.
如果将其更改为:
{ok, Device} = file:open(FileName, [Mode]), Device.
你的结果变成:
First line is "d1 and is program program the\n"
要获得最终结果,请将 read/1
函数更改为:
read(File) ->
case file:read_line(File) of
{ok, Data} ->
[First|Rest] = string:tokens(Data, " \t\n"),
[{First,string:join(Rest, "\t")} | read(File)];
eof -> []
end.
进行此更改后,您的程序会打印:
First line is {"d1","and\tis\tprogram\tprogram\tthe"}
其中第二个元素是一个字符串,其中的标记与原始数据中一样以制表符分隔。如果您希望第一个元素 "d1"
成为一个原子 d1
(我无法从您的问题中确定这是否是您想要的),您可以将其转换为 list_to_atom/1
.