【问题标题】:How to count unique users in file log?如何计算文件日志中的唯一用户?
【发布时间】:2012-06-17 19:59:24
【问题描述】:

给定一个txt日志文件,格式为:

USER_A timestamp1 otherstuff
USER_B timestamp2 otherstuff
USER_C timestamp3 otherstuff
USER_A timestamp4 otherstuff
USER_A timestamp5 otherstuff
USER_C timestamp6 otherstuff
USER_B timestamp7 otherstuff

您如何计算 erlang 中不同的唯一用户的数量?我正在考虑逐行读取文件并使用 proplists 模块。每个用户将是一个键,其值将是出现次数。读取文件后,我会调用:

length(proplists:get_keys(List)).

这是实现我的结果的正确方法吗?

【问题讨论】:

    标签: erlang


    【解决方案1】:

    我也会为此使用 sets 模块,因为它既快速又不包含重复项。

    以下代码应该可以完成这项工作:

    {ok,Bin} = file:read_file("test"),
    List = binary_to_list(Bin),
    Usernames = [hd(string:tokens(X," ")) || X <- string:tokens(List,[$\n])],
    sets:size(sets:from_list(Usernames)).
    

    编辑:我删除了单行,因为它没有增加任何价值

    【讨论】:

    • 请注意,这会将整个文件保存在内存中。从内存的角度来看,一次从文件中读取一行并将用户名添加到集合中可能会更好,例如在递归函数中。
    【解决方案2】:

    使用sets 模块中的集合来存储用户名然后使用sets:size/1 可能更合适。

    【讨论】:

      【解决方案3】:

      日志文件通常很大,因此请考虑在递归函数中一次一行地使用它:

      % Count the number of distinct users in the file named Filename                        
      count_users(Filename) ->
          {ok, File} = file:open(Filename, [read, raw, read_ahead]),
          Usernames = usernames(File, sets:new()),
          file:close(File),
          sets:size(Usernames).
      
      % Add all users in File, from the current file pointer position and forward,
      % to Set.
      % Side-effects: File is read and the file pointer is moved to the end.          
      usernames(File, Set) ->
          case file:read_line(File) of
              {ok, Line} ->
                  Username = hd(string:tokens(Line, " ")),
                  usernames(File, sets:add_element(Username, Set));
              eof ->
                  Set
          end.
      

      你可以这样称呼它:count_users("logfile")

      请注意,usernames/2 必须是 tail recursive 才能有效地工作。否则只会消耗更多内存。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-26
        • 2017-03-31
        • 1970-01-01
        • 1970-01-01
        • 2010-10-11
        • 2021-05-19
        相关资源
        最近更新 更多