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

Marked As Solved

pdgonzalez872

pdgonzalez872

Seems like calling String.replace/3 solves this nicely? Maybe I’m missing something.

ExUnit.start()

defmodule Test do
  use ExUnit.Case

  describe "implementation for https://forum.elixirforum.net/t/i-stuck-with-this-text-file-manipulation-problem/41384" do

    defmodule ReplaceVariablesImplementation do
      def call(text, %{name: name, company: company, time: time, salesguy: salesguy} = _args) do
        text
        |> String.replace("[name]", name)
        |> String.replace("[company]", company)
        |> String.replace("[time]", time)
        |> String.replace("[salesguy]", salesguy)
      end
    end

    test "Replaces variables in text" do
      # Do File.read!/1 to get the file contents. Using a variable for brevity.
      text = """
      Hi [name],
      Thank you for your time in our office.

      Thank you for booking at [company] for [time].

      Regards
      [salesguy]
      """

      # Using a string for time for brevity, maybe this is your use case, maybe not.
      args = %{name: "Jane", company: "", time: "2022/3/25 13:00", salesguy: "Joe"}

      expected = """
      Hi Jane,
      Thank you for your time in our office.

      Thank you for booking at  for 2022/3/25 13:00.

      Regards
      Joe
      """

      result = ReplaceVariablesImplementation.call(text, args)

      assert result == expected
    end
  end
end

(the test passes)

Also Liked

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.

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.

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

Where Next?

Popular in Questions Top

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
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
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
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
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
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
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
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement