ambareesha7

ambareesha7

I stuck with this text-file manipulation problem

i stuck with this problem,

i could read the text from text-file and index it but i could not update
I’m missing something

defmodule ReadText do
  def read_text_file(file_name) do
    case File.read(file_name) do
      {:ok, text} ->
        IO.puts("slice 1: #{String.slice(text, 3..8)}")
        slice1 = IO.gets("slice 1 to replace: ")
        String.replace(text, String.slice(text, 3..8), slice1, global: false)
        IO.puts("slice 2: #{String.slice(text, 72..80)}")
        slice2 = IO.gets("slice 2 to replace: ")
        String.replace(text, String.slice(text, 72..80), slice2, global: false)
        IO.puts("slice 3: #{String.slice(text, 86..91)}")
        slice3 = IO.gets("slice 3 to replace: ")
        String.replace(text, String.slice(text, 86..91), slice3, global: false)
        IO.puts("slice 4: #{String.slice(text, 101..110)}")
        slice4 = IO.gets("slice 4 to replace: ")
        String.replace(text, String.slice(text, 101..110), slice4, global: false)

      {:error, error} ->
        IO.puts(error)
    end
  end

  def get_replaceable_indexs(file_name) do
    case File.read(file_name) do
      {:ok, text} ->
        text
        |> String.split("")
        |> Enum.with_index(fn v, i -> [i, v] end)

      {:error, error} ->
        IO.puts(error)
    end
  end

  def open(file_path) do
    File.open(file_path, [:read, :write], fn text ->
      IO.read(text, :all)
    end)
  end
end

i tried in livebook to get dynamic index for square brockets and use this index as rang in String.slice(text, 3..8) but i’m missing the logic

i highly appreciate any help
thank you

First 10 of 17 Posts! Switch mode

al2o3cr

al2o3cr

Values in Elixir are immutable (they cannot be changed once created) - functions like String.replace return a new binary.

You can rebind variables, however. For instance,

  text = String.replace(text, String.slice(text, 72..80), slice2, global: false

After this line, the name text will refer to the result of String.replace instead of the original input.


General note: hardcoding numerical offsets that are passed to String.slice is very likely not what the problem is really looking for. Take a look at the Regex module for a better way to find sequences like “left square bracket followed by letters followed by right square bracket” and manipulate them.

dimitarvp

dimitarvp

Using string slices is absolutely not what you want here. I’d tell you that you failed the interview if you showed that to me.

Look for ways to search [anything] in the source text and replace that. Regex is a good start and might even be good enough as a final solution.

ambareesha7

ambareesha7

Yeah I know hard coding numbers are not the proper solution here and I have theoretical solution but struggling to implement that,

ambareesha7

ambareesha7

I’m a newbie getting into programming and trying my share of struggles, I’ll learn as I practice,
I’ll try regex functions

ericgray

ericgray

If I understand the problem correctly you need to replace variable placeholders like [name] with passed in arguments. You can use a Regex to solve this but if the structure of source.txt is exactly as it appears you can also use Elixir binary pattern matching. You can recurse over a binary file and match patterns like [name] [company] [time] [salesguy].

To keep things simple you can pass in a map as an argument

  %{name: "John", company: "Google", time: "3:30pm", salesguy: "Ralph"},

Now with binary pattern matching you can use this map to replace the placeholder variables.

defmodule Replacer do

  defp template do
    Application.app_dir(:replacer, "/priv/source.txt")
  end

  def replace_text(sample_data) when is_map(sample_data) do
    template()
    |> File.read!()
    |> replace(sample_data)
  end

  defp replace(source, sample_data) do
    replace(source, sample_data, [])
  end

  defp replace("", _sample_data, acc) do
    acc
    |> Enum.reverse()
    |> IO.iodata_to_binary()
  end

  defp replace(<<"[name]", rest::binary>>, sample_data, acc) do
    name = sample_data.name
    replace(rest, sample_data, [name | acc])
  end

  defp replace(<<"[company]", rest::binary>>, sample_data, acc) do
    company = sample_data.company
    replace(rest, sample_data, [company | acc])
  end

  defp replace(<<"[time]",  rest::binary>>, sample_data, acc) do
    time = sample_data.time
    replace(rest, sample_data, [time | acc])
  end

  defp replace(<<"[salesguy]",  rest::binary>>, sample_data, acc) do
    salesguy = sample_data.salesguy
    replace(rest, sample_data, [salesguy | acc])
  end

  defp replace(<<head, rest::binary>>, sample_data, acc) do
    replace(rest, sample_data, [head | acc])
  end

end

Now in iex you can

iex(1)>  sample_data = %{name: "John", company: "Google", time: "3:30pm", salesguy: "Ralph"}
iex(2)> iex(2)> Replacer.replace_text(record)
"Hi John,\nThank you for your time in our office.\nThanks for booking at Google for 3:30pm\nRegards\nRalph\n"
ambareesha7

ambareesha7

Thank you @ericgray it works and I’m trying on regex implementation,
still reading different regex and string related doc’s, articles

ericgray

ericgray

Great that’s a good way to learn. Try different things to see what works best for you. Regex patterns are good but they can be cryptic and hard to read. I think in this case where you know the shape of the data before hand binary pattern matching is easier in my opinion. Try a Regex and let us know what you come up with.

Aetherus

Aetherus

Suppose you have a map that stores the attributes you want to stuff into the template, like

attrs = %{
  "name" => "Charlie Bucket",
  "company" => "The Chocolate Factory",
  "time" => "Aug 12, 2021",
  "salesguy" => "Willy Wonka"
}

you can try

# `source` is the content read from `source.txt`
result =
  Enum.reduce(attrs, source, fn {key, value}, acc ->
    String.replace(acc, "[#{key}]", value, global: true)
  end)

or

result = 
  for {key, value} <- attrs, reduce: source do
    acc -> String.replace(acc, "[#{key}]", value, global: true)
  end
al2o3cr

al2o3cr

Given attrs:

attrs = %{
  "name" => "Charlie Bucket",
  "company" => "The Chocolate Factory",
  "time" => "Aug 12, 2021",
  "salesguy" => "Willy Wonka"
}

and an input string in source, a single call to Regex.replace can do this:

Regex.replace(~r/\[([^\]]+)\]/, source, fn _, key -> attrs[key] end)

This will silently replace unrecognized keys with empty strings; use something like Map.fetch if that isn’t desired.

The regex here looks worse than it is, because square brackets are metacharacters in regex:

  • \[ matches a literal open bracket
  • ([^\]]+) captures one or more characters that aren’t a ]
  • \] matches a literal close bracket
Aetherus

Aetherus

That’s faster than my solution, I guess, since it goes through the template string only once.

If the keys contain only word characters (i.e. a to z, A to Z, numbers, and _), the regex can be simplified as

~r/\[(\w+)\]/

Last Post!

ambareesha7

ambareesha7

Your code does the job
Actually I was overthinking on that issue, that’s why I posted it here but after I solved it, it was simple

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement