[Tutor] Possible to search text file for multiple string values at once?
bob gailer
bgailer at gmail.com
Fri Jan 23 19:38:50 CET 2009
Scott Stueben wrote:
> Hi all,
>
> I understand that python excels at text processing, and wondered if
> there is a way to use python to accomplish a certain task. I am
> trying to search large text files for multiple strings (like employee
> ID number, or name). Any text editor (I use Windows mostly) will
> certainly have a "find", "replace", or even "find in files" (to search
> multiple files for a value) function, but this is searching for one
> string at a time.
>
> I would like to search a text file for a list of strings, like a sql query.
>
> 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.
>
> But if you were in a SQL database, you could do something like:
>
> "SELECT * FROM my_table WHERE first_name IN ('Bob', 'John', 'Joe',
> 'Jim', 'Fred')"
>
> and you would get results for all five values.
>
> I would love to set up a script to parse a file and show results from
> a list of strings. Is this possible with python?
>
Yes - and also possible with almost all other programming languages.
Here is one of several ways to do it in Python:
for first_name in ('Bob', 'John', 'Joe', 'Jim', 'Fred'):
if first_name in text:
print first_name, 'found'
--
Bob Gailer
Chapel Hill NC
919-636-4239
More information about the Tutor
mailing list