1

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

    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)).

愿它很容易失败。刚开始使用erlang。

4

2 回答 2

1

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

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

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

 Bla = string:tokens(binary_to_list(hd(Data))," ,."),
于 2012-12-16T02:24:05.053 回答
1

也可以在不将其转换为列表的情况下拆分二进制文件:

Bla = binary:split(Data, [<<" ">>, <<",">>, <<".">>], [global])

(请参阅binary:split/3 的文档。)

于 2012-12-17T10:04:24.057 回答