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

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
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

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52341 488
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New

We're in Beta

About us Mission Statement