从erlang中的字符串中提取数据

时间:2013-01-26 19:12:47

标签: erlang

我用这种语法声明了Line变量:

Line =“1; nabil; chouaib; france; 27”,

我想声明5个变量: Id,Firsname,lastname,address,age

Id应包含1 Firsname应包含nabil 姓氏应该包含chouaib 地址应包含法国 年龄应该包含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, ";") 

我认为的类型不是字符串(但在显示此行的错误之前的consol中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).

1 个答案:

答案 0 :(得分:7)

您可以使用string:tokens/2函数和pattern match列表将字符串拆分为字符串列表以提取变量:

1> [IdStr, Firstname, Lastname, Address, AgeStr] = string:tokens(Line, ";").
["1","nabil","chouaib","france","27"]

然后可以使用list_to_integer/1函数将IdStr和AgeStr转换为整数:

2> Id = list_to_integer(IdStr).
1
3> Age = list_to_integer(AgeStr).
27