elang 字符处理

%%%
%%% 1 判断是否是字符串
%%% 2 从文件中提取中文
%%%
%%%
%%%



%%-----------------------------------------------------------------------------------
%% 1 判断是否是字符串
is_string([]) -> yes;
is_string(List) -> is_string(List, non_unicode).

is_string([C|Rest], non_unicode) when C >= 0, C =< 255 -> is_string(Rest, non_unicode);
is_string([C|Rest], _) when C =< 65000 -> is_string(Rest, unicode);
is_string([], non_unicode) -> yes;
is_string([], unicode) -> unicode;
is_string(_, _) -> no.

%%-----------------------------------------------------------------------------------
%% 2 从文件中提取中文
%% 假设src.txt内容为:
%% hello 自由!
%% 2012年5月22日
%% cheng

run(Src) ->
    {ok, Fd} = file:open(Src, [raw, binary]),
    do_match(Fd).

do_match(Fd) ->
    Zh = do_match(Fd, 1, []),
    file:write_file("zh.txt", lists:reverse(Zh)).

do_match(Fd, LineNo, Acc) ->
    case file:read_file(Fd) of
        eof ->
            Acc;
        {ok, Line} ->
            case re:run(Line, "[\x{4e00}-\x{9fff}]+",[unicode, global]) of
                nomatch ->
                    do_match(Fd, LineNo + 1, Acc);
                {match, MatchL} ->
                    L =
                        [begin 
                             B = binary:part(Line, Pos, Len),
                             ["L", erlang:integer_to_list(LineNo)," ", B, "\n"]
                         end || [{Pos, Len}] <- MatchL],
                    do_match(Fd,LineNo + 1, L ++ Acc)
            end;
        {error, _Reason} ->
            io:format("read line error: ~w",[_Reason]),
            Acc
    end.

 

posted @ 2013-09-24 21:26  wangjunshusheng  阅读(331)  评论(0)    收藏  举报