roganjoshua

roganjoshua

Guards or pattern matching processing a text file - =~

I am trying to process a text file like a kind of plain text guitar tab with etc. a bit like the Ultimate Guitar Tab site.
Each line will either blanks or chords or lyrics or something like that.

defmodule TextFileProcessor do
  def process_file(file_path) do
    File.stream!(file_path)
    |> Enum.each(&process_line/1)
  end

  defp process_line(line) when line =~ ~r/^LYRICS:/ do
    # Process lines starting with "LYRICS:"
    IO.puts("Processing lyrics line: #{line}")
  end

  defp process_line(line) when line =~ ~r/^CHORDS:/ do
    # Process lines starting with "CHORDS:"
    IO.puts("Processing chords line: #{line}")
  end

  defp process_line(line) do
    # Default processing for other lines
    IO.puts("Processing line: #{line}")
  end
end

I can’t use =~ in a guard or other Kernel functions is there a better way to do this?

I hope there is enough in here.

TIA

Marked As Solved

derpycoder

derpycoder

Here’s my take on it:

"""
LYRICS: L1
CHORDS: C1
LYRICS: L2
CHORDS: C2
CHORDS: C3
CHORDS: C4
CHORDS: C5
CHORDS: C6
TEMPO: T1
foobar\
"""
|> String.split("\n")
|> Enum.map_reduce(%{}, fn line, acc ->
  hd = line |> String.split(":") |> hd()

  {line, if(hd in ["LYRICS", "CHORDS", "TEMPO"]) do
      Map.update(acc, hd, [line], fn arr -> [line | arr] end)
  else
      Map.update(acc, "REST", [line], fn arr -> [line | arr] end)
  end}
end)
|> then(fn {_lines, acc} -> acc end)

or if you don’t care about specifics in the first iteration, you can do:

"""
LYRICS: L1
CHORDS: C1
LYRICS: L2
CHORDS: C2
CHORDS: C3
CHORDS: C4
CHORDS: C5
CHORDS: C6
TEMPO: T1
foobar\
"""
|> String.split("\n")
|> Enum.map_reduce(%{}, fn line, acc ->
  hd = line |> String.split(":") |> hd() || "REST"

  {line, Map.update(acc, hd, [line], fn arr -> [line | arr] end)}
end)
|> then(fn {_lines, acc} -> acc end)

Both the pipelines, spit out an organized map, which you can then process.

%{
  "CHORDS" => ["CHORDS: C6", "CHORDS: C5", "CHORDS: C4", "CHORDS: C3", "CHORDS: C2", "CHORDS: C1"],
  "LYRICS" => ["LYRICS: L2", "LYRICS: L1"],
  "REST" => ["foobar"],
  "TEMPO" => ["TEMPO: T1"]
}

If you don’t want that map, you can directly process it within the pipeline above.


P.S.

  1. Instead of split, you can use regex.
  2. Instead of if-else, you can use cond.

Personally, I prefer this way because it makes it composable and allows me to use dbg() to see if anything in the pipeline is not working as expected.

Also Liked

dimitarvp

dimitarvp

I am pretty late here but I’d advise against regexes unless they are very straightforward. Haven’t looked into yours in details (and length is not always an indicator of a complex regex) but I’d probably reach for nimble_parsec and give it a go for a day or two.

That being said, being productive in that particular library is a skill in and of itself so if you are pressed for time you should probably keep your regex solution but also add edge case unit tests.

christhekeele

christhekeele

Not in guards/function heads. You’ll need to use a single function with something like a cond inside.

roganjoshua

roganjoshua

If anyone is interested I think I kind of got to where I wanted like this:

defmodule Textprocessor do
  @regex_find_chords ~r/\b(?:[BE]b?|[ACDFG]#?)(?:sus|m|maj|min|[-1-9\/m])?(?:sus|m|maj|min|[-1-9\/m])?\b#?/
  @empty_line ~r/^\s*$/
  @instruction ~r/^\[[\w+ ]+\]\s*$/

  @moduledoc """
  Documentation for `Textprocessor`.
  """

  @doc """
  Process song

  ## Examples
    # iex> Textprocessor.process_file("./lyrics.text")
    # :ok
  """

  def process_file(filename) do
    File.stream!(filename)
    |> Enum.map(&String.trim/1)
    |> Enum.each(&process_line/1)
  end

  defp process_line(line) do
    cond do
      String.match?(line, @regex_find_chords) ->
        IO.puts("CHORDS: #{line}")

      String.match?(line, @instruction) ->
        IO.puts("INSTRUCTION: #{line}")

      String.match?(line, @empty_line) ->
        IO.puts("EMPTY: #{line}")

      true ->
        IO.puts("LYRICS: #{line}")
        :ok
    end
  end
end

Not sure this is optimal but I would be interested in any criticism

Where Next?

Popular in Questions Top

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
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
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
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
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
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
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
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
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

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
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
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
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
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
hariharasudhan94
Lets say i have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => "XX...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement