读取TXT文件内容并将其解析为Erlang元组的最佳方法是什么?

htrmnn0y  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(150)

I've got a TXT file in the form of tuples:

{187,386,858}.
{46,347,621}.
{28,856,354}.
{246,298,574}.
{979,964,424}.
{664,722,318}.
{82,69,64}.

I need to read the file, so i get a list of usable tuples to pass {Key, Num1, Num2} to a function.
I have tried using binary:split , but that doesn't get me quite there:

{ok, Device} = file:read_file(Filename),
    Tuples = [binary_to_list(Bin) || Bin <- binary:split(Device,<<".\n">>,[global])].

I will get a result like this:

["{187,386,858}","{46,347,621}","{28,856,354}",
 "{246,298,574}","{979,964,424}","{664,722,318}",
 "{82,69,64}","{654,351,856}","{185,101,57}","{93,747,166}",
 "{41,442,946}","{444,336,300}","{951,589,376}",
 "{193,987,300}",[]]

but looking to get something more in this format:

[{979, 193, 224}, {365, 339, 950}, {197, 586, 308},
 {243, 563, 245}, {795, 534, 331}, {227, 736, 701},
 {111, 901, 185}, {303, 178, 461}, {361, 212, 985},
 {149, 659, 496}, {612, 375, 311}, {896, 402, 10}]
qf9go6mv

qf9go6mv1#

您可以使用file:consult/1直接从文件中解析Erlang术语。

lkaoscv7

lkaoscv72#

您可以尝试:

1> Device = <<"{187,386,858}.\n{46,347,621}.\n{28,856,354}.\n{246,298,574}">>.
2> Lists = [binary:split(binary:part(Bin, 1, byte_size(Bin) - 2), <<",">>, [global]) || Bin <- binary:split(Device,<<".\n">>,[global])].
3> Res = [list_to_tuple([binary_to_integer(B) || B <- L]) || L <- Lists].
4> Res.
[{187,386,858},{46,347,621},{28,856,354},{246,298,574}]

相关问题