字符串后的erlang异常:文件中读取行上的令牌

字符串后的erlang异常:文件中读取行上的令牌,erlang,Erlang,试图将从文件中读取的行剪切成字符串列表。这总是导致一个我不知道如何解决的异常 exception error: no function clause matching string:tokens1 (<<"Cascading Style Sheets CSS are an increasingly common way for website developers to control the look\n">>," ,.",[]) in function re

试图将从文件中读取的行剪切成字符串列表。这总是导致一个我不知道如何解决的异常

    exception error: no function clause matching string:tokens1
(<<"Cascading Style Sheets CSS are an increasingly common way for website developers to control the look\n">>," ,.",[]) in function  readTest:run/1



-module(readTest).
-export([run/1]).

open_file(FileName, Mode) ->
    {ok, Device} = file:open(FileName, [Mode, binary]),
    Device.

close_file(Device) ->
    ok = file:close(Device).

read_lines(Device, L) ->
    case io:get_line(Device, L) of
        eof ->
            lists:reverse(L);
        String ->
            read_lines(Device, [String | L])
    end.

run(InputFileName) ->
    Device = open_file(InputFileName, read),
    Data = read_lines(Device, []),
    close_file(Device),
    io:format("Read ~p lines~n", [length(Data)]),
    Bla = string:tokens(hd(Data)," ,."),
    io:format(hd(Data)).
异常错误:没有与字符串匹配的函数子句:tokens1
函数readTest中的(,“,.”,[])运行/1
-模块(读取测试)。
-导出([run/1])。
打开文件(文件名、模式)->
{ok,Device}=file:open(文件名,[模式,二进制]),
装置。
关闭\u文件(设备)->
确定=文件:关闭(设备)。
读线(设备,L)->
案例io:get_line(设备,L)的
eof->
清单:反向(L);
字符串->
读取_行(设备,[String | L])
结束。
运行(输入文件名)->
设备=打开文件(输入文件名,读取),
数据=读取线(设备,[]),
关闭_文件(设备),
io:格式(“读取~p行~n”,[长度(数据)],
Bla=字符串:标记(hd(数据),“,.”,
io:格式(hd(数据))。

但愿这很容易失败。在erlang中刚刚开始。

当您打开带有二进制标志的文件时,行被读取为二进制文件,而不是列表(字符串)。 所以在你的代码中

 Bla = string:tokens(hd(Data)," ,."),
hd(Data)实际上是一个二进制文件,这会导致string:tokens崩溃。 您可以从file:open中删除二进制标志,或者显式地将二进制转换为list:

 Bla = string:tokens(binary_to_list(hd(Data))," ,."),

也可以拆分二进制文件而不将其转换为列表:

Bla = binary:split(Data, [<<" ">>, <<",">>, <<".">>], [global])
Bla=binary:split(数据,[,],[global])
(见附件。)