I will try to keep this example very specific and simple. Let us say I have a text file called file.txt, with path C:/Ruffle/bunch-of-files/file.txt, and with content as follows:

Hello, XXX, you YYY!

And I have also got two files containing ordered lists, namely names.txt and epithets.txt, both in directory C:/Ruffle/bunch-of-lists/ and with content as follows:

{John, Mary, Algernon}

{Honey Biscuit, Old Twit, Wonderful Person}

What do I need to put in a short Mathematica notebook that

  • imports file.txt
  • applies specified rules to choose an element from names.txt and another from epithets.txt (for example, let's say in one case it chooses an element randomly and in the other it chooses the nth where n = 1 + Mod[DateList[][[3]], 3])
  • substitutes them for "XXX" and "YYY" respectively
  • saves the result as C:/Ruffle/bunch-of-amended-files/amended-file.txt
  • closes file.txt


(The reason I have assigned this question an HTML tag as well as a text one is that what I need is to output HTML files. So amended-file.txt would actually be amended-file.html, and the Mathematica notebook would also have to insert a specified header and tags. But since an HTML file is only a text file, the problem is one of text processing, and I am trying to keep the question as simple as possible.)

  • 1
    $\begingroup$ It might ease things a bit if your text files use the conventional template format for Mathematica strings: tmp = StringTemplate["Hello, `name`, you `epiphet`!"];. With that, tmp @ <|"name" -> "John", "epiphet" -> "old twit"|> will generate the desired sentence. $\endgroup$ Aug 23, 2017 at 11:48
  • $\begingroup$ 1) see FileTemplateApply and friends, or StringReplace 2) consider storing values in separate file rather than notebooks which only make extracting them problematic 3) where are you stuck? $\endgroup$
    – Kuba
    Aug 23, 2017 at 11:49
  • $\begingroup$ Thanks. I have edited the question so that names and epithets are stored in text files rather than notebooks, but I will have to think on this further before specifying better where I'm stuck. $\endgroup$
    – user51827
    Aug 23, 2017 at 12:00

1 Answer 1

OutputForm@"Hello, XXX, you YYY" >> file.txt
{"John", "Mary", "Algernon"} >> names.txt
{"Honey Biscuit", "Old Twit", "Wonderful Person"} >> epithets.txt
    Import["file.txt", "Text"]
  , { "XXX" -> RandomChoice@Get@"names.txt"
    , "YYY" -> Get["epithets.txt"][[1 + Mod[DateList[][[3]], 3]]]
 ] // OutputForm >> amended-file.txt

Hello, XXX, you YYY

Hello, Algernon, you Wonderful Person

p.s. OutputForm is used to drop quote marks when string is Put. Alternative would be Export[#, "Text"]&.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.