473,327 Members | 1,919 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

string search function

Hi,
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.

Thanks.

-g
-----

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
break
else: # boolean 'or' search
found = False
for f in fterms:
if f in stext:
found = True
break

return found

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

if bsearch(terms, stext, btype):
print 'found'
else:
print 'not found'
Jul 18 '05 #1
2 2369
On 23 Jul 2004, gyromagnetic wrote:
Are there improvements that can be made to the code below? Are there
better alternatives?


There are two ways I can think of:

1)

You can replace the 'or' search with a regular expression:

import re

def bsearch(fterms, stext, btype='AND'):
if btype == 'AND': # boolean 'and' search
...
else: # boolean 'or' search
found = bool(re.search(fterms.join('|'),stext))

return found

Assuming Python's regexps are somewhat optimized, this should be about the
fastest search you can get with arbitrary strings. Unfortunately, there's
no direct 'and' equivalent with regexps (it can be done, but it's helluva
ugly). If you want to optimize 'and', you'll need to use whatever
advanced algorithms our friends at Google use ;)

2)

Assuming your search terms don't contain whitespace, and you want to
compare only entire words (not substrings), replace the string search with
a list search, simply by adding the line 'stext = stext.split()' to the
top of the search function. This will greatly speed up the search by
avoiding checking partial words. The same effect can be achieved with the
regexp above by appending '\s' to the beginning and end of it.

Continuing along this line (whole words, no whitespace), you can replace
the lists with sets for an even greater speedup. The resulting code would
look like this (with a bit of code stolen from sets.py):

from sets import Set

def ispartialsubset(self, other):
"""Report whether another set contains at least one member of this set."""
self._binary_sanity_check(other)
for elt in ifilter(other._data.has_key, self):
return True
return False

Set.ispartialsubset = ispartialsubset

def bsearch(fterms, stext, btype='AND'):
stext = stext.split()
if btype == 'AND': # boolean 'and' search
found = Set(fterms).issubset(Set(stext))
else: # boolean 'or' search
found = Set(fterms).ispartialsubset(Set(stext))
return found

If the same stext or fterms is used multiple times, you could move the
..split() and/or the Set() transformations outside of the function, so they
only have to be done once.

Again, this method (using sets) only works if your words contain no
whitespace, and you're not interested in matching parts of words. It's
/much/ faster than a string search, though.

Hope this helps!

Jul 18 '05 #2
You should take a look at regular expressions (re)
functions. I think you will find that they are
much more efficient and can handle things your
routines can't handle.

http://www.amk.ca/python/howto/regex/

HTH,
Larry Bates
Syscon, Inc.

"gyromagnetic" <gy**********@excite.com> wrote in message
news:46**************************@posting.google.c om...
Hi,
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.

Thanks.

-g
-----

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
break
else: # boolean 'or' search
found = False
for f in fterms:
if f in stext:
found = True
break

return found

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

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

Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Anand Pillai | last post by:
To search a word in a group of words, say a paragraph or a web page, would a string search or a regexp search be faster? The string search would of course be, if str.find(substr) != -1:...
4
by: Ken Fine | last post by:
I'm looking to find or create an ASP script that will take a string, examine it for a search term, and if it finds the search term in the string, return the highlighted search term along with the...
9
by: Durgesh Sharma | last post by:
Hi All, Pleas help me .I am a starter as far as C Language is concerned . How can i Right Trim all the white spaces of a very long (2000 chars) Charecter string ( from the Right Side ) ? or how...
3
by: Imran Aziz | last post by:
Hello All, I am getting the following error on our production server, and I dont get the same error on the development box. Unable to cast object of type 'System.Byte' to type 'System.String'. ...
2
by: Badass Scotsman | last post by:
Hello, Using VB and ASP,NET I would like to be able to search a STRING for a smaller STRING within, based on the characters which appear before and after. For example: String1 = " That was...
21
by: gary | last post by:
How would one make the ECMA-262 String.replace method work with a string literal? For example, if my string was "HELLO" how would I make it work in this instance. Please note my square...
5
by: int main(void) | last post by:
Hi all, Following is my attempt to write a string search and replace function. #include <stdio.h> #include <stdlib.h> #include <string.h>...
10
by: B. Williams | last post by:
I have an assignment that requires me to write a program that uses a class, a constructor, a switch, and store the records in a text file. The second requirement is to create a function called...
5
by: mosscliffe | last post by:
I am looking for a simple split function to create a list of entries from a string which contains quoted elements. Like in 'google' search. eg string = 'bob john "johnny cash" 234 june' and...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.