python-like style

Bengt Richter bokr at oz.net
Thu Aug 22 23:40:46 EDT 2002


On Wed, 21 Aug 2002 17:01:07 +0200, Giorgi Lekishvili <gleki at gol.ge> wrote:

>Hi all!
>
>Description of my task:
>Given a file. Given a list of keywords.
>Task:
>test whether a keyword is in the line and return the NEXT line. More
>precisely, the list of all such lines.
>
>Of course, I can do it ina n OO manner.
>
>Anyway, I would like to do it in a functional manner.
>Here comes, what I was trying to do.
>>>>f=open(fn, 'r')
>>>>i=iter(f)
>>>>def getit(it, kw):
>...     if string.find(it, kw)>0:
>...         return it.next()
>...     else:
>...         return 0
>>>>kw='<'
>>>>rz=filter(None, map(apply(getit, s, kw), i))
>
>No, the traceback:
>File "D:\Python22\wxPython\tools\boa\ExternalLib\PythonInterpreter.py",
>line 65, in push
>    exec code in self.locals
>  File "<console>", line 1, in ?
>exceptions.NameError : name 's' is not defined
>
>Thanks in advance.
>Greetings,
>Giorgi
>
>PS. I am using Py 2.2.x, Boa.
>
Are you wondering what "name 's' is not defined" means?

I suggest you test each of your results in the interaction above to
see that they are, and behave as, what you think. There is no traceback
until the last statement, so that is a good candidate for checking from
the inside out, expression-wise, starting with the 'apply'. When you have
a complex nested expression statement, break it into a simple equivalent series
of statements, e.g.,

    >>>>rz=filter(None, map(apply(getit, s, kw), i))
    apply_result = apply(getit, s, kw)
    map_result = map(apply_result, i)
    rz = filter(None, map_result)

Then check each intermediate result (assuming something doesn't already strike you as fishy ;-)


Another possibility for the problem (using 2.2):
(This is a little different from yours, since the returned lines
are also tested for the keyword. I'll leave it as an exercise to
eliminate thse lines if desired).

 >>> class HadKW:
 ...     def __init__(self, kw):
 ...         self.kw = kw
 ...         self.last_had_kw = 0
 ...     def __call__(self, line):
 ...         had_it = self.last_had_kw
 ...         self.last_had_kw = line.find(self.kw)>=0
 ...         if had_it: return line
 ...         else: return None
 ...
 >>> filter(HadKW('test'), file('test.txt'))
 ['one\n', 'test three\n', 'four\n']
 >>> filter(HadKW('\n'), file('test.txt'))
 ['one\n', 'test two\n', 'test three\n', 'four\n', 'five\n', '\n']
 >>> filter(HadKW('o'), file('test.txt'))
 ['test two\n', 'test three\n', 'five\n']

 >>> file('test.txt').readlines()
 ['test.txt\n', 'one\n', 'test two\n', 'test three\n', 'four\n', 'five\n', '\n']

Regards,
Bengt Richter



More information about the Python-list mailing list