[Tutor] Template long text substitution
Dave Angel
davea at ieee.org
Tue Aug 25 01:36:26 CEST 2009
Stefan Lesicnik wrote:
> Hi Guys,
>
> I am trying to do the following, and im not sure how to deal with a blob of
> text.
>
> I have the following file i am using as a template
>
> %%NAME%%
> %%NUMBER%%
> %%REPORT%%
>
> and i have a corresponding file with values
>
> name="bob"
> number="123"
> report="report is long
> and spans multiple
> lines. It also is already in the exact format
> i want to replace the above template var %%REPORT%% with"
>
> The report part is obviously the problem. My code so far reads line by line
> and splits on the = and reads the values into a dict.
>
> file = open('test','r')
> data = {}
> for line in file:
> line = line.strip()
> line = line.split('=')
> data[line[0]] = line[1]
>
> My intention is then to replace the %%NAME%% with data['name'] etc.
> If it makes a difference, the report= will be generated by another program
> and given to me in the exact format i need to substitute it into %%REPORT%%.
> (or i can put it in that file).
>
> I hope this makes sense, thanks in advance - i really do appreciate it :)
>
> Stefan
>
>
There's much more left unsaid here. In order to parse that file, you
have to know exactly what it will contain. I'll ask a few questions
that might help you narrow it down.
Currently you have three keywords "name" "number" and "report". Do you
want this to be variable, and the order arbitrary? Clearly, you want to
be case insensitive, since your template file has different case than
the data file.
Will there always be quotes around the value? Your current code doesn't
check for them, nor does it remove them. But you do have to decide for
the third keyword when the text ends. One way could be "till end of
file" but I'm guessing you don't want that, especially if order is
irrelevant. Another way could be "till another line with an '=' sign
occurs". But what happens if you want an equal sign in the text
someday? Or you could end when you encounter the next quote mark. But
what happens if you want an embedded quote in the substituted text?
If you have some choice in the file format, you could change it to
specify the keywords with double-percent signs, same as in the template
file. Then the rule could be that any line that starts with a percented
keyword is the start of a new keyword, and any other line is appended
(with newline between) to the previous value.
DaveA
More information about the Tutor
mailing list