代码之家  ›  专栏  ›  技术社区  ›  smaug

如何在erlang中将文本文件读入映射?

  •  1
  • smaug  · 技术社区  · 6 年前

    我有一个这样的文本文件:

    {fruit, [apple,banana,kiwi]}.
    {car, [estate,hatchback]}.
    {tree, [ebony,pine,ask,birch]}.
    {planet, [earth]}.
    

    如何将其读入erlang中的映射或任何其他数据结构(进一步迭代每个键及其各自的值)并最终打印映射?

    2 回复  |  直到 6 年前
        1
  •  7
  •   Hynek -Pichi- Vychodil Paulo Suassuna    6 年前
    $ cat > things.txt
    {fruit, [apple,banana,kiwi]}.
    {car, [estate,hatchback]}.
    {tree, [ebony,pine,ask,birch]}.
    {planet, [earth]}.
    $ erl
    Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
    
    Eshell V9.3  (abort with ^G)
    1> {ok, L} = file:consult("things.txt").
    {ok,[{fruit,[apple,banana,kiwi]},
         {car,[estate,hatchback]},
         {tree,[ebony,pine,ask,birch]},
         {planet,[earth]}]}
    2> maps:from_list(L).
    #{car => [estate,hatchback],
      fruit => [apple,banana,kiwi],
      planet => [earth],
      tree => [ebony,pine,ask,birch]}
    
        2
  •  1
  •   Eugen Dubrovin    6 年前

    这个对我有用

    -module(test). 
    -export([start/0, scan_string/1]). 
    
    start() -> 
       {ok, File} = file:open("Newfile.txt",[read]),
       {ok, List} = file:read(File,1024 * 1024),
       KeyVal = scan_string(List),
    
       F = fun({K,V}, Acc) -> maps:put(K, V, Acc) end,
       lists:foldl(F, #{}, KeyVal).
    
    scan_string(TermString) ->
        {_, Strings} = lists:foldl(fun break_terms/2, {"", []}, TermString),
        Tokens = [T || {ok, T, _} <- lists:map(fun erl_scan:string/1, Strings)],
        AbsForms = [A || {ok, A} <- lists:map(fun erl_parse:parse_exprs/1, Tokens)],
        [V || {value, V, _} <- lists:map(fun eval_terms/1, AbsForms)].
    
    break_terms($., {String, Lines}) ->
        Line = lists:reverse([$. | String]),
        {"", [Line | Lines]};
    break_terms(Char, {String, Lines}) ->
        {[Char | String], Lines}.
    
    eval_terms(Abstract) ->
        erl_eval:exprs(Abstract, erl_eval:new_bindings()).
    

    newfile.txt文件=

    {fruit, [apple,banana,kiwi]}.
    {car, [estate,hatchback]}.
    {tree, [ebony,pine,ask,birch]}.
    {planet, [earth]}.
    

    壳牌=

    Eshell V9.3.1  (abort with ^G)
    1> c(test).
    {ok,test}
    2> test:start().
    #{car => [estate,hatchback],
      fruit => [apple,banana,kiwi],
      tree => [ebony,pine,ask,birch]}
    3>