[Tutor] Possible to search text file for multiple string values at once?

Kent Johnson kent37 at tds.net
Fri Jan 23 19:52:26 CET 2009


On Fri, Jan 23, 2009 at 1:25 PM, Scott Stueben <sidewalking at gmail.com> wrote:

> I would like to search a text file for a list of strings, like a sql query.

What do you want to do if you find one? Do you want to get every line
that contains any of the strings, or a list of which strings are
found, or just find out if any of the strings are there?

> For instance:  To search a text file for the values 'Bob', 'John',
> 'Joe', 'Jim', and 'Fred', you would have to open the dialog and do
> five separate searches.  Lots of copying and pasting, lots of room for
> typos.

You can do this with a regular expression. For example,

import re
findAny = re.compile('Bob|John|Joe|Jim|Fred')

for found in findAny.findall(s):
  print found

will print all occurrences of any of the target names.

You can build the regex string dynamically from user input; if
'toFind' is a list of target words, use
findAny = re.compile('|'.join(re.escape(target) for target in toFind))

re.escape() cleans up targets that have special characters in them.


More information about the Tutor mailing list