我用这种语法声明了 Line 变量:
Line =“1;nabil;chouaib;法国;27”,
我想声明 5 个变量:Id 、 Firsname 、 lastname 、 address 、 age
Id 应包含 1 Firsname 应包含 nabil 姓应包含 chouaib 地址应包含 france 年龄应包含 27
所以我必须解析变量Line的内容
在这种情况下,分隔符是;
我有这个功能:
test()->
ForEachLine = fun(Line,Buffer)->
io:format("Line: ~s~n",Line),
[IdStr, FirstnameStr, LastnameStr, AddressTr, AgeStr] = string:tokens(Line, ";"),
Buffer end,
InitialBuffer = [],
csv:parse("/var/lib/mysql/test/person1.csv",ForEachLine,InitialBuffer).
但是当我执行测试功能 T 有这个错误:
1> model:test().
Line: 1;nabil;chouaib;france;27
** exception error: no match of right hand side value [["1;nabil;chouaib;france;27"]]
in function model:'-test/0-fun-0-'/2
in call from csv:start_parsing/3
问题与此行有关:
[IdStr, Firstname, Lastname, Address, AgeStr] = string:tokens(Line, ";")
我认为Line的类型不是字符串(但在错误之前的控制台中显示此行 Line: 1;nabil;chouaib;france;27
)
所以我应该只知道Line的类型
csv.erl 模块是:
%%% --- csv parser in Erlang. ------
%%% To help process large csv files without loading them into
%%% memory. Similar to the xml parsing technique of SAX
-module(csv).
-compile(export_all).
parse(FilePath,ForEachLine,Opaque)->
case file:open(FilePath,[read]) of
{_,S} ->
start_parsing(S,ForEachLine,Opaque);
Error -> Error
end.
start_parsing(S,ForEachLine,Opaque)->
Line = io:get_line(S,''),
case Line of
eof -> {ok,Opaque};
"\n" -> start_parsing(S,ForEachLine,Opaque);
"\r\n" -> start_parsing(S,ForEachLine,Opaque);
_ ->
NewOpaque = ForEachLine(scanner(clean(clean(Line,10),13)),Opaque),
start_parsing(S,ForEachLine,NewOpaque)
end.
scan(InitString,Char,[Head|Buffer]) when Head == Char ->
{lists:reverse(InitString),Buffer};
scan(InitString,Char,[Head|Buffer]) when Head =/= Char ->
scan([Head|InitString],Char,Buffer);
scan(X,_,Buffer) when Buffer == [] -> {done,lists:reverse(X)}.
scanner(Text)-> lists:reverse(traverse_text(Text,[])).
traverse_text(Text,Buff)->
case scan("",$,,Text) of
{done,SomeText}-> [SomeText|Buff];
{Value,Rem}-> traverse_text(Rem,[Value|Buff])
end.
clean(Text,Char)->
string:strip(string:strip(Text,right,Char),left,Char).