简体   繁体   中英

Counting word occurences from an external file and display them using Erlang?

I am having trouble fully understanding how to count how many times an element occurs within a text file. I am able to read the file in like so -

-module(list3).

-export([readlines/1]).

readlines(FileName) ->
{ok, Device} = file:open(FileName, [read]),
try get_all_lines(Device)
  after file:close(Device)
end.

get_all_lines(Device) ->
case io:get_line(Device, "") of
    eof  -> [];
    Line -> Line ++ get_all_lines(Device)
end.

I would transfer the text file into a list of strings and I understand that list:length or foldl would normally count the number of elements within a list returning overall how many words there would be, however, I would like to list the words within the file and how many times it has occurred. Would this be done through pattern matching? The only solution that I can currently think of would require a lot of code.

Any tips will be appreciated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM