Searching a file for multiple strings

gotbyrd gotbyrd at gmail.com
Mon Feb 2 21:02:46 EST 2009


On Jan 31, 2:45 pm, Tim Chase <python.l... at tim.thechases.com> wrote:
> > I'm fairly new with python and am trying to build a fairly simple
> > search script.  Ultimately, I'm wanting to search a directory of files
> > for multiple user inputted keywords.  I've already written a script
> > that can search for a single string through multiple files, now I just
> > need to adapt it to multiple strings.
>
> > I found a bit of code that's a good start:
>
> > import re
> > test = open('something.txt', 'r').read()
>
> > list = ['a', 'b', 'c']
>
> > foundit = re.compile('|'.join(re.escape(target) for target in list))
> > if foundit.findall(test):
> >     print 'yes!'
>
> > The only trouble with this is it returns yes! if it finds any of the
> > search items, and I only want a return when it finds all of them.  Is
> > there a bit of code that's similar that I can use?
>
> [insert standard admonition about using "list" as a variable
> name, masking the built-in "list"]
> Unless there's a reason to use regular expressions, you could
> simply use
>
>    test = open("something.txt").read()
>    items = ['a', 'b', 'c']
>    if all(s in test for s in items):
>      print "Yes!"
>    else:
>      print "Sorry, bub"
>
> This presumes python2.5 in which the "all()" function was added.
>   Otherwise in pre-2.5, you could do
>
>    for s in items:
>      if s not in test:
>        print "Sorry, bub"
>        break
>    else:
>      print "Yeparoo"
>
> (note that the "else" goes with the "for", not the "if")
>
> -tkc

Thanks, Tim.  What you suggested worked perfectly!

Jason



More information about the Python-list mailing list