[Tutor] Add newline's, wrap, a long string

David david at abbottdavid.com
Wed Apr 29 20:05:30 CEST 2009


Alan Gauld wrote:
> 
> "Sander Sweers" <sander.sweers at gmail.com> wrote
> 
>> What you can do is define all the variables upfront. This way you can
>> get rid of the else. Below is an example how you can do this with only
>> looping once over the fle.
> 
> And you can put the variables as keys of a dictionary and avoid all the 
> if tests:
> 
> data = {'CBUILD':None,             'ACCEPT_KEYWORDS: None,
>             ....
>            }
> 
>> for line in fname:
>      for keyphrase in data:
>>           if keyphrase in line:
>>               output = line.split('"')[1]
>>               data[keyphrase] = textwrap.fill(output, 80)
> 
> 
I don't know how else to describe it, that is so cool :)
[code]
#!/usr/bin/python

import textwrap
data = {'CBUILD':None, 'CFLAGS':None, 'MAKEOPTS':None}
def get_use():
     fname = open('/tmp/comprookie2000/emerge_info.txt')
     for line in fname:
         for keyphrase in data:
             if keyphrase in line:
                 output = line.split('"')[1]
                 data[keyphrase] = textwrap.fill(output, 80)
     fname.close()

get_use()

CBUILD = data['CBUILD']
CFLAGS = data['CFLAGS']
MAKEOPTS = data['MAKEOPTS']


print 'CBUILD =',CBUILD
print 'CFLAGS =',CFLAGS
print 'MAKEOPTS =',MAKEOPTS


[output]
CBUILD = x86_64-pc-linux-gnu
CFLAGS = -march=opteron -O2 -pipe
MAKEOPTS = -j3

Thanks Alan Martin, Sander, hope I did it correctly.


-- 
Powered by Gentoo GNU/Linux
http://linuxcrazy.com


More information about the Tutor mailing list