Extracting values from text file
Mirco Wahab
wahab at chemie.uni-halle.de
Fri Jun 16 15:21:17 EDT 2006
Thus spoke Preben Randhol (on 2006-06-16 10:36):
> A short newbie question. I would like to extract some values from a
> given text file directly into python variables. Can this be done simply
> by either standard library or other libraries? Some pointers where to
> get started would be much appreciated.
I used your example just to try that in python
(i have to improve my python skills), but waved
the white flag after realizing that there's no
easy string/var-into-string interpolation.
I tried to build some parser table
which will then translate hings into a dictionary
v_apples = '\b\S+';
v_ducks = '\b\S+';
v_butter = '\b\S+';
rg_ar = [ "Apples (v_apples)" ,
"(v_ducks) Ducks" ,
"(v_butter) butter" ]
the above interpolation won't work, so I gave up.
To give an idea what I intended, I'll add
the short perl script which I took as a
blue print for my python effort (your
example text may be used):
my @filter = ( # define filter table
"Apples (apples)",
"(ducks) Ducks",
"(butter) g butter",
);
my %varname = (); # variable names will be found in text
my $example = do { local$/; <DATA> }; # read the appended example text
# change <DATA> to <> for std input
for (@filter) { # iterate over filter rules
if( s/\((.+)\)/\\b(\\S+?)\\b/ ) { # pull out variable names ($1)
my $v = $1; # and replace them by '\b(\S)\b'
$varname{$v} = $1 if $example =~ /$_/; # pull values from
} # text to varnames
}
your text prints then:
(for (keys %varname) { print "$_\t=>\t$varname{$_}\n"; })
apples => 34
butter => 0.5
ducks => 56
with variable names taken from your text:
__DATA__
An example text file:
-----------
Some text that can span some lines.
Apples 34
56 Ducks
Some more text.
0.5 g butter
-----------------
Above will do the job in perl, but I have no idea
how to translate this to python, especially, as I
said, the string-to-string interpolation thing for
the build-up regex.
Maybe some experts may help out?
Regards
Mirco
More information about the Python-list
mailing list