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.com/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.

Where Next?

Popular in Questions Top

jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
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
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
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
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
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
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
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

Other popular topics Top

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
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
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
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
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

We're in Beta

About us Mission Statement