Extracting values from text file
Mirco Wahab
wahab at chemie.uni-halle.de
Sun Jun 18 04:54:01 EDT 2006
Thus spoke Dennis Lee Bieber (on 2006-06-18 06:29):
> On Sun, 18 Jun 2006 03:12:23 +0200, Mirco Wahab
> <wahab at chemie.uni-halle.de> declaimed the following in comp.lang.python:
>> - you have to explicitly instantiate a dictionary value
>> (with 0) if/before you want in-place add to it (why is that?)
> Uhm... Not quite...
> ...
> dict.get(key, default)
>
> returns the value associated by key, IFF key exists in the
> dictionary, otherwise it returns the value defined for default.
Thanks, Dennis, for your help on this part I bragged about.
Now the extractor loop, according to your suggestion, can
be written shorter:
for rule in filter:
k = re.search(r'\((.+)\)', rule) # pull out variable names ->k
if k.group(1): # pull their values from text
varname[k.group(1)] = varname.get(k.group(1), 0) + float( \
re.search( re.sub(r'\((.+)\)', varscanner, rule), \
example ).group(1) ) # use regex in modified 'rule'
For the other issue I stumbled upon:
- no DWIM-ism (do what I mean) on 'value' addition
a = '1'
a += '1.1111'
print a
will print
11.1111
and not 2.1111, as in 'dynamically typed', 'operator based' languages.
(maybe the lack of a simple string-concatenation operator is the reason?)
whereas:
a = '1'
a += 1.1111
print a
will fail magnificently. These thing would come handy
when working with text/table driven computations (as above)
How could one approach these things without needing to
get too explicitly about 'type conversions'
(Python is supposed to be 'dynamically typed'?).
Regards & thanks
Mirco
More information about the Python-list
mailing list