string search function

gyromagnetic gyromagnetic at
Fri Jul 23 16:08:56 CEST 2004

I have written a function that searches a text string for various
words. The text is searched using a boolean 'and' or a boolean 'or' of
the input list of search terms.

Since I need to use this function for many long strings and many
search words, I would like to use as efficient a method as possible.

Are there improvements that can be made to the code below? Are there
better alternatives?
I am currently using Python 2.3.




def bsearch(fterms, stext, btype='AND'):
    if btype == 'AND':         # boolean 'and' search
        found = True
        for f in fterms:
            if f not in stext:
                found = False
    else:                       # boolean 'or' search
        found = False
        for f in fterms:
            if f in stext:
                found = True

    return found

if __name__ == '__main__':
    stext = "hello to you all"
    terms = ['hello', 'goodbye']
    btype = 'OR'

    if bsearch(terms, stext, btype):
        print 'found'
        print 'not found'

More information about the Python-list mailing list