[Tutor] Re: this is ugly

Andrei project5 at redrival.net
Tue Oct 21 18:05:26 EDT 2003


Alan Gauld wrote:
>>Can line 3 of the following be improved (especially since I might
> 
> want
> 
>>to search for even more strings within each line):
>>
>>myfile=open(r'F:\logs\myfile.txt', 'r')
>>for line in myfile.readlines():
>>   if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or
>>line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1:
>>         #code if found
> 
> 
> Yes use a regular expression. You can combine conditions in one
> expression and it will only search the string once instead of
> once per condition.
> 
> I'll leave it to someone else to explain how to combine the
> regexs! I'm going to bed and my brain is tired.... :-)

Well, here's a RE which would match any of those things:

   KeC 923|ZEF 156|pBX 88347|FZX 17255

I don't know if evaling that regex would be faster/easier than using the 
find methods, especially not with one of the shortcut notations 
mentioned earlier in this thread. Perhaps a more generic RE would be in 
order, e.g.:

   \S{3}\s\d{3,5}

which (if compiled with the IGNORECASE flag) matches any sequence of 3 
letters followed by a space and 3 to 5 digits. Of course I don't know 
the type of input, perhaps this would match more than desired.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.





More information about the Tutor mailing list