[Tutor] Substitution problem
Kent Johnson
kent37 at tds.net
Tue Feb 21 23:30:24 CET 2006
Srinivas Iyyer wrote:
> Dear group,
> I am trying to automate a process in statistical
> language R.
>
> There for 1 operation 50 lines of code is written.
> This process query postgres database and does some
> processing on the resulting data and writes back a
> file.
>
> I want to replicate the 50 line code, 90 times, by
> substituting with postgres.table_id and file name at 2
> places.
> I want to read File_A, loop through it and substitute
> $MOL_ID = 1 and $MOL_NAME = A
>
> I want to reproduce 50 lines * 90 times substituting
> ID and NAME by looping through File_A.
>
>
> I tried using re module, I do not know if this correct
> or wrong.
>
>
> for m in file_A:
> cols = m.split('\t')
> molid = cols[0].strip()
> molname = cols[1].strip()
> for k in file_B:
> pat1 = '$MOL_ID'
> pat2 = '$MOL_NAME'
> if re.search(pat1,k):
> s = Template(k)
> s.substitute($MOL_ID,molid)
> if re.search(pat2,k):
> t = Template(k)
> t.substitute($MOL_NAME,molname)
>
>
> However, this is not working, somehow.
You don't need regexes for this, string replace will do what you want.
>>> s =
'''write.table(mol_towrite,"$MOL_NAME_adj_pval",sep='t',quote=F,col.names=F)'''
>>> s2 = s.replace('$MOL_NAME', 'my data')
>>> s2
'write.table(mol_towrite,"my data_adj_pval",sep=\'t\',quote=F,col.names=F)'
Your program could
- read all of file B with open('file_B').read()
- for each line of file A
- split the line
- substitute for '$MOL_ID' and '$MOL_NAME'
- write the modified string to your output file
BTW $ is a special character in a regex, you need to escape it as \$
>
> Can any one help me please. If more simple methods are
> available please show a new way.
You might take a look at RPy, it would probably let you do all the work
in a Python program instead of writing an R code generator.
Kent
More information about the Tutor
mailing list