本文主要講為文字建立索引,通過使用程序字典的方式為文字建立索引,儘管專家提倡盡量避免使用程序字典,但是在初學階段很容易地就使用了程序字典,當然,除了程序字典方式外,還有其它方式,後面章節我將會使用另外一種方式來儲存單詞、行數、出現次數,也即erlang提供的模組:ets(erlang term storage),後面我們會發現,使用ets更加方便。
練習:為文字建立索引。
要求:給定乙個由英文單詞構成的檔案,為檔案中所有單詞建立索引,記錄每個單詞出現的行號和每行出現的次數,並將索引存入乙個檔案。
-module執行結果示意圖:(控制輸出每行索引結果)(text_index).
-export([indexer/2]).
-import(re, [run/2,replace/4]).
-import(string,[substr/3]).
indexer(filein,fileout) -> =file:open(filein,read),
iffirst =:= ok ->erase(),
l = readall(fileout,second,0),
io:format("~nsuccess:~p~n",[l]);
first =/= ok ->io:format("open file error: file doesn't exist!")
end.
readall(fileout, s,lineno) ->updatelineno = lineno +1,
oneline = io:get_line(s,''),
ifoneline =:= eof ->io:format("read file eof!"),
file:close(s);
oneline =/= eof ->[index(fileout,oneline,updatelineno) |readall(fileout,s,updatelineno)]
end.
index(file,term,lineno) ->reg ="[a-za-z-']+",
case re:run(term,reg,) of
nomatch ->dict =get(),
%%io:format("第(~p)行後索引列表:~p~n",[lineno,dict]),
io:format("/********第~p行顯示開始********/",[lineno]),
showinfo(lineno,dict),
unconsult(file,dict);
]} ->word = string:substr(term,start+1,length),
l =get(word),
ifl =:= undefined ->put(word,),
%io:format("1---word:~p value:~p ~n",[word,get(word)]),
newterm = re:replace(term,word,"?",),
index(file,newterm,lineno);
l =/= undefined ->= lists:nth(1,l),
ifln =:= lineno ->dl =lists:delete(,l),
newl = [ |dl],
put(word,newl),
newterm = re:replace(term,word,"?",),
%io:format("2---new term:~s~n",[newterm]),
index(file,newterm,lineno);
ln =/= lineno ->newl = [|l],
put(word,newl),
%io:format("3---l:~p newl:~p word:~p value:~p~n",[l,newl,word,get(word)]),
newterm = re:replace(term,word,"?",),
index(file,newterm,lineno)
endend
end.
unconsult(file,l) -> =file:open(file,write),
lists:foreach(
fun(x) -> io:format(s,"~p.~n",[x]) end
, l),
file:close(s).
showinfo(lineno,) ->io:format("~n/*****第~p行顯示結束********/~n",[lineno]);
showinfo(lineno,dict) ->first = lists:nth(1,dict),
=first,
io:format("~n單詞:~p>>>~n",[word]),
showindex(l),
showinfo(lineno,lists:delete(first,dict)).
showindex() ->word_end;
showindex(l) ->first = lists:nth(1,l),
=first,
io:format(" 出現行號:~p 出現次數:~p ",[lineno,num]),
showindex(lists:delete(first,l)).
執行完畢後,索引結果檔案內容:(文件索引存放形式為:,]} )
Erlang實戰練習(四)
通過前幾次的練習實踐相信大家對erlang程式設計有了基本的認識和了解,本文通過二分搜尋 echo server 程序環三個實戰練習認識erlang中程序的通訊的基礎,通過本次實戰,主要是感受erlang建立程序 傳送訊息 接受訊息的過程,我們知道,erlang並不是共享記憶體的通訊,erlang中...
erlang基礎練習 排序
module sort export bubble 1,select1 1,select2 1 氣泡排序法 第一種 bubble l bubble sort l,length l 1 bubble sort l,0 l bubble sort h t num result bubble once h...
erlang初學小練習
module delive compile export all sum x,y if x 9,y 9 io format w w w n x,y,x y x y io format w w w x,y,x y sum x,y 1 x y io format w w w n x,y,x y sum ...