[Tutor] Looking for Words - Help

Peter Otten __peter__ at web.de
Fri Oct 11 17:23:22 CEST 2013


Mark Lawrence wrote:

> On 11/10/2013 15:23, Peter Otten wrote:
>> Alan Gauld wrote:
>>
>>>> Use the stripw() function we saw on individual words to make
>>>> finding hits more accurate
>>>
>>> No idea what that means but since the assignment suggests
>>> it we should assume its correct.
>>
>> My crystal ball says
>>
>> def stripw(word):
>>      return word.strip('",.')
>>
>> or somesuch.
>>
>>> You have several bad habits in here...
>>>
>>>> def lines(name, word):
>>>>       'print all lines of name in which word occurs'
>>>>
>>>>       infile = open(name, 'r')
>>>>       lst = infile.readlines()
>>>>       infile.close()
>>>
>>> You could do that in one line:
>>>
>>>          lst = open(name).readlines()
>>
>> Talking about bad habits -- what you are suggesting here is a step in the
>> wrong direction.
>>
>> If at this point in the OP's Python career you bother about how to open
>> and close a file at all you should recommend the safe variant
>>
>> with open(name) as infile:
>>      lines = infile.readlines()
>>
>> rather than the version for, err, us lazy old bastards ;)
>>
> 
> Why bother building a list when the modern idiom is simply
> 
> for line in infile: ?

Without context the question would rather be "When should you build a list 
of lines from a file?" and the right answer is "Hardly ever" while the 
pragmatic answer is "It doesn't matter unless your file is 'big'". As to the

with open(name) as infile:
    for line in infile.readlines(): # wrong! use 'for line in infile: ...
        ...

idiom the only way to get rid of that is to remove the readlines() method.

See also http://bugs.python.org/issue13510

To bring this back on topic, I recommended a list of words because that is 
easier to handle for a newbie than a generator, but if you (reader, not 
Mark) are an intermediate Python user and know about generators you can try 
to implement a generator like

def context(items, is_match, nbefore=1, nafter=1):
   """
   >>> list(context([-1, 2, 3, -1, 4, -1], lambda item: item < 0))
   [[-1, 2], [3, -1, 4], [4, -1]]
   """

that stores only nbefore + nafter + 1 items.




More information about the Tutor mailing list