kimc0de

kimc0de

Read data from a text file and generate a map

Hi all, I have a .txt file with information like this
11111 0
11112 1
11113 2
11114 3
11115 4
11116 5
11121 6
11122 7

66664 zzgl
66665 zzz
66666 zzzz

What I have to do:

  1. read the file
  2. return a map like this
    %{
    “11111” => “0”
    “11112” => “1”
    “11113” => “2”

    “66664” => “zzgl”
    “66665” => “zzz”
    “66666” => “zzzz”
    }

Here’s what I have tried

def get_map(file_name) do
      {:ok, file} = File.read(file_name)
      # create a new map
      result_map = %{}

     # create a map with key = first word of the line and value = second word of the line
      file
      |> String.split("\n")
      |> Enum.map(fn line -> String.split(line, " ") end)
      |> Enum.reduce(result_map, fn [key, value], acc -> Map.put(acc, key, value) end)
    end

I got something returned but with errors.

** (FunctionClauseError) no function clause matching in anonymous fn/2 in DiceWare.get_map/1    
    The following arguments were given to anonymous fn/2 in DiceWare.get_map/1:
    
        # 1
        [""]
    
        # 2
        %{
          "42464" => "manila",
          "45512" => "osmose",
          "63122" => "unicri",
          "31645" => "heimat",
          "52552" => "riegel",
          "41251" => "leimt",
          "55144" => "sierra",
          "11223" => "44",
          "16131" => "bruch",
          "35413" => "kniend",
          "41211" => "lehmig",
          "45154" => "oase",
          "31261" => "habe",
          "32216" => "hetzte",
          "51641" => "rang",
          "64456" => "wenden",
          "26435" => "gitter",
          "36232" => "krung",
          "35163" => "kkkk",
          "55213" => "sinus",
          "21533" => "donau",
          "63116" => "uni",
          "53222" => "rosten",
          "23533" => "fakten",
          "12323" => "abu",
          "34462" => "kauer",
          "13412" => "anzug",
          "23241" => "ernte",
          "61324" => "teilt",
          "63653" => "vwx",
          "44422" => "neogen",
          "66312" => "zhd",
          "45354" => "onyx",
          "11416" => "500",
          "64212" => "wamme",
          "53351" => "ruhm",
          "52316" => "regime",
          "63421" => "verl",
          "25266" => "fuerst",
          "24311" => "fichte",
          "24432" => "fj",
          "23654" => "faulig",
          "12646" => "alias",
          "14333" => "baryon",
          "21655" => "dronte",
          "36513" => "lagern",
          "11662" => "$",
          "42343" => "magnat",
          "53424" => "russig",
          "55555" => "spleen",
          ...
        }
    
    (elixirexercise01 0.1.0) lib/diceware.ex:24: anonymous fn/2 in DiceWare.get_map/1
    (elixir 1.14.1) lib/enum.ex:2468: Enum."-reduce/3-lists^foldl/2-0-"/3
        }

I don’t really understand what I’ve done wrong, why does the map start from the middle of the file?
what do I have to change to make it work?

Marked As Solved

adamu

adamu

There’s probably a newline at the end of the file that you didn’t account for.

Try String.trim() before String.split("\n"), or do String.split("\n", trim: true).

P.S. Posting this during Advent of Code is fortunate timing :grin:

Also Liked

mruoss

mruoss

I’d do something like this. You might have to Stream.reject empty lines or so…

file_name
|> File.stream!()
|> Stream.map(&String.split/1)
|> Stream.map(&List.to_tuple/1)
|> Enum.into(%{})

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement